2

Why this works? I mean, accessing the private variable.

 class Test { private $q = 0; public function __construct() { $this->q = 1; } public static function EpicConstruct() { $test = new self(); $test->q = 2; return $test; } } $test = Test::EpicConstruct(); 
3
  • 3
    Because you're accessing it from the same class. Commented Mar 19, 2013 at 21:07
  • 1
    php.net/manual/en/language.oop5.visibility.php Commented Mar 19, 2013 at 21:08
  • Think about it like a men's and women's locker room. Objects of the same class can see each other's privates. Commented Mar 19, 2013 at 21:55

1 Answer 1

3

Because you are accessing the member in the correct context, namely: the class that defines the private member.

Sign up to request clarification or add additional context in comments.

2 Comments

So i can work with any object of this class this way? I think i understand how decorator pattern works now. Thanks!
@smsteel As long as it is the same class: yes. With the decorator pattern, not so much: as a decorator is a class that either extends the class, or, more typically, extends/implements a common supertype (some base class or interface). The former kind of decorator will only have access to members that are at least protected, the latter only to public members of the class (or protected members of the supertype).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.