Search code examples
phpobjectprivateprotected

PHP protected and private properties?


I have a class in PHP that upon an instance being created takes an instance of itself as an argument. A mock of the class is below.

abstract class AAA {

    protected $_a;
    protected $_b;

    public function __construct($a, $b) {

         $this->_a = $a;
         $this->_b = $b;
    }
}

class BBB extends AAA {

    private $_aaa;

    public function __construct($a, $b, AAA $aaa) {

        parent::__construct($a, $b);
        $this->_aaa = $aaa;
    }
}

Within a method of BBB I have full access to the protected properties of $aaa. An example of this is below.

# BBB method
public function getAAAprotected() {

    return array(
        '_a' => $this->_aaa->_a,
        '_b' => $this->_aaa->_b,
    );
}

I am confused as to how this can be. My understanding of protected properties were that they can only be accessed by extended classes within that instance or have I been wrong all of this time.

Could someone please explain, or give direction, so that I can fully understand when or not a protected/private method/function are just that?


Solution

  • Objects of the same type will have access to each others private and protected members even though they are not the same instances. This is because the implementation specific details are already known when inside those objects.

    http://php.net/manual/en/language.oop5.visibility.php#language.oop5.visibility-other-objects