This isn't perfect (see here for my inspiration and why it's not), but it's a start:
class Person {
var $name;
var $sex;
function Person() {
$this->name = "Jon";
$this->sex = "male";
}
function __get($name) {
$var_name = "";
foreach ($GLOBALS as $key => $val) {
if ($val === $this) {
$var_name = $key;
break;
}
}
echo "Getting undefined '$name' from '\$$var_name'.
";
$trace = debug_backtrace();
trigger_error(
'Undefined property via __get(): ' . $name .
' in ' . $trace[0]['file'] .
' on line ' . $trace[0]['line'],
E_USER_NOTICE);
return null;
}
}
$oPerson = new Person();
$name = $oPerson->name;
$fullname = $oPerson->fullname;
For example, the following won't work:
class Nerd {
var $person;
function Nerd() {
$person = new Person();
$nerd_fullname = $person->fullname;
}
}
because the $person
property of Nerd
is not global, so it doesn't appear in $GLOBALS
, nor is it within the scope of Persons
's magic function __get()
.