Class Invasion

Objects of the same type have access to each others private and protected features (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 X {
    private $p = "abc";
    private const X = 'def';

    private function privateMethod() { echo __METHOD__; }

    function foo(X $x) {
        echo $x->p;
        echo $x::X; // also works on constant, though less useful
    }

    function set($s) {
        $this->p = $s;
    }

    function goo() {
     // The current object ($this) calls the local object's private method
     $x = new X;
     $x->privateMethod();
    }
}

$x1 = new x;
$x1->set('xyz');

$x2 = nex x;
$x2->foo($x1);
// display xyzdef

// class invasion between sibling classes
class parent {
    // Necessary. Could be abstract too.
    protected function execute() { echo __METHOD__; }
}

class sister extends parent {
    // cannot be called outside of y or x
    protected function execute() { echo __METHOD__; }
}

class brother extends parent {
    // calling a sister's class method
    function foo($y) { $y->execute(); }
}

(new brother)->foo(new sister);

?>

Documentation

See also Invading private properties and methods in PHP

Related : Classes, Visibility

Related packages : spatie/invade