Saturday, February 19, 2011

PHP __get and Private class variables

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?

From stackoverflow
  • 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

  • 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.

0 comments:

Post a Comment