Class Invasion
Objects of the same type have access to each others private and protected features, like properties, constants and methods, even though they are not the same instances.
This means that the host object of a class A can call any method and property on a different object of the same class.
It also works between siblings class. When the called method is defined in the parent class, protected methods are also accessible that way.
Class invasion works on private and protected methods, properties and constants.
Class invasion doesn’t work when running an external closure inside the class.
<?php
// Example of Host class accessing local object (direct class invasion)
class Elephpant {
private $p = 'abc';
private const HABITAT = 'def';
private function privateMethod() { echo __METHOD__; }
function sniff(Elephpant $other) {
echo $other->p;
echo $other::HABITAT; // also works on constant, though less useful
}
function set($s) {
$this->p = $s;
}
function mirrorTest() {
// The current object ($this) calls the local object's private method
$elephpant = new Elephpant;
$elephpant->privateMethod();
}
}
$matriarch = new Elephpant;
$matriarch->set('xyz');
$calf = new Elephpant;
$calf->sniff($matriarch);
// display xyzdef
// class invasion between sibling classes
class theParent {
// Necessary. Could be abstract too.
protected function execute() { echo __METHOD__; }
}
class sister extends theParent {
// cannot be called outside of a sibling class instance
protected function execute() { echo __METHOD__; }
}
class brother extends theParent {
// calling a sister's class method
function greetSibling($sibling) { $sibling->execute(); }
}
(new brother)->greetSibling(new sister);
?>