2017-07-12 33 views
1

我試圖將reference設置爲objectfunctionPHP - 獲取對象的函數的參考

我試過你可以在way 2上看到沒有成功。

對此有何建議?

<? 
function echoc($data) { 
    echo "\n<pre>\n"; 
    print_r($data); 
    echo "</pre>\n"; 
} 

class Person { 

    const STATUS_SLEEPING = 0; 
    const STATUS_EATING  = 1; 
    const STATUS_SEEING  = 2; 
    const STATUS_WALKING = 3; 

    function __construct() { 
     $this->status = self::STATUS_SLEEPING; 
    } 
    function see() { 
     $this->status = self::STATUS_SEEING; 
     echo 'I\'m seeing now!'; 
    } 
    function eat($what) { 
     $this->status = self::STATUS_EATING; 
     echo 'I\'m eating '.$what.' now!'; 
    } 
    function walk() { 
     $this->status = self::STATUS_WALKING; 
     echo 'I\'m walking now!'; 
    } 
    function getStatus() { 
     return $this->status; 
    } 
    function getStatusStr() { 
     switch ($this->status) { 
      case self::STATUS_SLEEPING: return 'STATUS_SLEEPING'; 
      case self::STATUS_EATING: return 'STATUS_EATING'; 
      case self::STATUS_SEEING: return 'STATUS_SEEING'; 
      case self::STATUS_WALKING: return 'STATUS_WALKING'; 
     } 
    } 

}; 

$p = new Person(); 
echoc('Status: '.$p->getStatusStr()); 

$p->see(); 
echoc('Status: '.$p->getStatusStr()); 

$p->walk(); 
echoc('Status: '.$p->getStatusStr()); 


$way = 2; 

switch ($way) { 
    case 1: 
     $p->eat('piza'); 
     break; 
    case 2: 
     $method = 'eat';     // the name of the function is stored on a variable 
     // begin of code I'm looking for 
     $callback = $p->$method;   // I tried this with no success 
     // end of code I'm looking for 
     call_user_func($callback, 'pizza'); // this line cannot be changed. I'm not allowed to 
     break; 
} 

echoc('Status: '.$p->getStatusStr()); 

?> 

回答

0

你所尋找的是:

$callback = [$p, 'eat']; // Callback: $p->eat() 

call_user_func($callback, 'pizza'); // Run $p->eat('pizza'); 
+0

僅供參考,你也可以這樣做: '$方法= '吃'; ' '$ p - > $ method('pizza');' –

+0

謝謝,工作! – Angel