tags:

views:

4836

answers:

2

Assuming one has an abstract base class "foo" with __get() defined, and a child class "bar" which inherits from foo with a private variable $var, will the parent __get() be called when trying to access the private $var from outside the class?

+7  A: 

Yes.

<?php
    abstract class foo
    {
        public function __get($var)
        {
            echo "Parent (Foo) __get() called for $var\n";
        }
    }

   class bar extends foo
   {
        private $var;
        public function __construct()
        {
            $this->var = "25\n";
        }

        public function getVar()
        {
            return $this->var;
        }
    }

    $obj = new bar();
    echo $obj->var;
    echo $obj->getVar();
?>

output:

$ php test.php

Parent (Foo) __get() called for var

25

Electronic Zebra
+3  A: 

Yes. __get() and __set() (and __call() for that matter) are invoked when a data member is accessed that is not visible to the current execution.

In this case, $var is private, so accessing it publically will invoke the __get() hook.

Peter Bailey