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;
}
}
?>
See Also
- Accessing private properties from other instances
- Class Invasion Both Ways
- How to easily access private properties and methods in PHP