Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP __get and Private class variables

Tags:

oop

php

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?

like image 915
Electronic Zebra Avatar asked Nov 11 '08 21:11

Electronic Zebra


People also ask

How can you assign values to private variables of another class in PHP?

Use the __setter (__set) function to set value(s) to your private variable inside a the class, and when the value is needed, use the __getter (__get) function to return the values.

What is __ get in PHP?

From the PHP manual: __set() is run when writing data to inaccessible properties. __get() is utilized for reading data from inaccessible properties.

What is __ method __ in PHP?

__FUNCTION__ and __METHOD__ as in PHP 5.0.4 is that. __FUNCTION__ returns only the name of the function. while as __METHOD__ returns the name of the class alongwith the name of the function.

Can private variables be inherited in PHP?

No; since $privattrib is private, Base's version and Derived's version are completely independent.


2 Answers

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

like image 187
Electronic Zebra Avatar answered Oct 22 '22 07:10

Electronic Zebra


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 publicly will invoke the __get() hook.

like image 37
Peter Bailey Avatar answered Oct 22 '22 06:10

Peter Bailey