In the following example
class Employee
{
var $name;
var $city;
protected $wage;
function __get($propName)
{
echo "__get called!<br />";
$vars = array("name","city");
if (in_array($propName, $vars))
{
return $this->$propName;
} else {
return "No such variable!";
}
}
}
$employee = new Employee();
$employee->name = "Mario";
echo $employee->name."<br />";
echo $employee->age;
The output is:
Mario
__get called!
No such variable!
… confuses me, I understand that “__get called!” appears when $employee->name is accesed, but why does it not appear even when $employee->age is accesed? I mean… it’s there but it seems like the __get considers only the return in the if-else statement. How is that possible?
Observation : Of course __get runs when it detects $age does not exist when read, but …when it does run, why doesn’t the echo in it work?
Conclusion: the “__get called!” appeared because of one call of __get, that in which $employee->age is read.
Your assumptions are wrong.
No, it doesn’t.
__getis only invoked when you attempt to access a member which does not exist. You have defined a publicly accessible member named$name, this is what the linevar $namedoes. Reading/writing to$employee->namewill never invoke the magic__getor__set_methods.It is not
$employee->namethat is causing"__get called"to be printed;$employee->nameis returning"Mario", the value you assigned to that member, and that is what is being printed. It is$employee->agethat is causing"__get called"to be printed.I’ve tried to better explain the lines and what they do in respect to
__get:RE: Your observation
The echo does work. The reason you are only seeing one
"__get called!"is because__getis only called once, by attempting to access$employee->age.