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?
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.
From the PHP manual: __set() is run when writing data to inaccessible properties. __get() is utilized for reading data from inaccessible properties.
__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.
No; since $privattrib is private, Base's version and Derived's version are completely independent.
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 publicly will invoke the __get()
hook.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With