PHP - 获取对象函数的引用

时间:2017-07-12 02:49:12

标签: php oop

我试图reference function object {/ 1}}。

我尝试了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());

?>

1 个答案:

答案 0 :(得分:0)

您正在寻找的是:

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

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