2012-08-23 55 views
1

對於某些用戶級別的調試,我想知道從哪個變量調用某個類的某個屬性。所有課程都是stdClass,所以我不能在這個方向尋找答案。從屬性被調用的地方獲取變量

比方說,我有一個類Person與屬性NameSex。該設置看起來像$oPerson = new Person()。當我撥打$oPerson->FirstName = 'Jack';我想弄清楚電話是從$oPerson發出的。這可以實現嗎?

回答

0

這是不完美的(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()範圍內。