-2

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
SolarSync
  • 109
  • 7
  • Haha a downvote seriously? Why do people who take a question with a seemlessly easy answer for themselves, as a pointless question. – SolarSync Sep 09 '14 at 20:38
  • Either I need sleep or you just answered your own question – Jhecht Sep 09 '14 at 20:39
  • I was unsure how the visibility of properties/methods within a class fundamentally works. I don't think I answered that. :) – SolarSync Sep 09 '14 at 20:44

1 Answers1

2

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

Weltschmerz
  • 2,166
  • 1
  • 15
  • 18