Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Object Invasion

PHP allows objects of one class to access private structures of an object of the same class.

This is useful when cloning or importing objects with __set_state(): within the same class, those methods can create new objects and assign all their properties.

This feature break OOP encapsulation: even when using private visibility, it is possible to access then from outside the object.

<?php

class Elephpant {
    private $trunkLength = 0;

    // accessing a different object
    function trumpet(Elephpant $elephpant) {
        $elephpant->trunkLength = $this->trunkLength;
    }

    function __set_state($array) {
        $object = new self();
        $object->trunkLength = $array['trunkLength'];

        return $object;
    }
}

?>

Documentation

See Also