Search code examples
phpmagic-methods

PHP - use __get with $this


Usually if I have an object $foo and I want to intercept the access to one of its property, let's say bar, when using $foo->bar, I can use the magic method __get.

From what I can see (here) __get does not work when interactiong with $this. I find this kind of odd and inconsistent.

What is the reason beyond this behaviour?


Solution

  • __get() is only invoked if a property with the given name cannot be found on the object. In your example $this->a resolves to the protected property $a which is accessible from the context of the class. That's why __get() is not called in this case.

    This has nothing to do with using $this.

    class A {
        public $a = 'A'; // $a is public
    
        public function __get($name) {
            return 'B';
        }
    }
    
    $a = new A();
    var_dump($a->a); // string(1) "A" and not "B"
    
    class B {
        protected $b = 'B'; // $b is protected
    
        public function __get($name) {
            return 'C';
        }
    }
    
    $b = new B();
    var_dump($b->b); // string(1) "C" and not "B"
    
    class C1 {
        private $c = 'C';
    }    
    
    class C2 extends C1 {
        public function __get($name) {
            return 'D';
        }
    }
    
    $c = new C2();
    var_dump($c->c); // string(1) "D" and not "C"