dtah63820 2017-07-12 02:49
浏览 44
已采纳

PHP - 获取对象函数的引用

I'm trying to get a reference to a function of an object.

I tried what you can see on the way 2 with no success.

Any advice on this?

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

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());

?>
  • 写回答

1条回答 默认 最新

  • dthtvk3666 2017-07-12 03:03
    关注

    What you are looking for is:

    $callback = [$p, 'eat']; // Callback: $p->eat()
    
    call_user_func($callback, 'pizza'); // Run $p->eat('pizza');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?