从存储为类成员的字符串调用类方法


Calling class method from string stored as class member

我正在尝试调用存储为$_auto的方法,但它不起作用。

<?php
    class Index {
        private $_auto;
        public function __construct() {
            $this->_auto = "index";
            $this->_auto();
        }
        public function index() {
            echo "index";
        }
    }
    $index = new Index();
?>
您需要

使用 call_user_func 来执行此操作:

call_user_func(array($this, $this->_auto));

不幸的是,PHP 不允许你直接使用属性值作为可调用对象。

还有一个技巧可以用来自动调用这样的可调用对象。我不确定我会认可它,但它就在这里。将__call的实现添加到类中:

 public function __call($name, $args)
 {
     if (isset($this->$name) && is_callable($this->$name)) {
         return call_user_func_array($this->$name, $args);
     }
     else {
         throw new 'Exception("No such callable $name!");
     }
 }

这将允许你调用可调用对象,所以你可以调用自由函数:

 $this->_auto = 'phpinfo';
 $this->_auto();

和类方法:

 $this->_auto = array($this, 'index');
 $this->_auto();

当然,您可以通过调整__call调用的内容来自定义此行为。

您的代码正在尝试调用名为"_auto"的方法。 要做你所要求的,你想让方法名称成为一个php变量,或者类似于其他海报所说的内容。

class Foo {
    private function _auto() {
        echo "index";
    }
    public function callmethod($method) {
        $this->$method();
    }
}
$foo = new Foo();
$foo->callmethod('_auto');
你没有

一个名为 _auto() 的方法,你只有一个名为 $_auto 的属性。如果你的目的是调用未定义的方法以返回名称相似的属性(如果存在),则需要编写一个__call()魔术方法来执行查看名称相似的属性并返回值的逻辑。 因此,需要将这样的东西添加到您的类中:

public function __call($called_method, $arguments) {
    if(property_exists($this, $called_method)) {
        return $this->{$called_method};
    } else {
        throw new Exception('Illegal method call.');
    }
}

我认为您错误地将"_auto"定义为属性?

尝试使用:

private function _auto(){}

而不是

private $_auto