這是不完美的(see here for my inspiration and why it's not),但它是一個開始:
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'.\n";
$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;
例如,以下將不起作用:
class Nerd {
var $person;
function Nerd() {
$person = new Person();
$nerd_fullname = $person->fullname;
}
}
因爲Nerd
的$person
屬性不全球,所以它不出現在$GLOBALS
,也不在Persons
的魔術功能__get()
範圍內。
來源
2012-08-23 13:43:02
Jon