从存储为类成员的字符串中调用类方法 [英] Calling class method from string stored as class member
问题描述
我正在尝试调用存储为$_auto
的方法,但是它将不起作用.
I am trying to call a method stored as $_auto
, but it will not work.
<?php
class Index {
private $_auto;
public function __construct() {
$this->_auto = "index";
$this->_auto();
}
public function index() {
echo "index";
}
}
$index = new Index();
?>
推荐答案
您需要使用 call_user_func
为此:
You need to use call_user_func
to do this:
call_user_func(array($this, $this->_auto));
不幸的是,PHP不允许您直接将属性值用作可调用项 callables .
Unfortunately PHP does not allow you to directly use property values as callables.
还有一个技巧可以用来自动调用这样的可调用对象.我不确定我会支持它,但是确实如此.将__call
的此实现添加到您的课程中:
There is also a trick you could use to auto-invoke callables like this. I 'm not sure I would endorse it, but here it is. Add this implementation of __call
to your class:
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 will allow you to invoke callables, so you can call free functions:
$this->_auto = 'phpinfo';
$this->_auto();
和类方法:
$this->_auto = array($this, 'index');
$this->_auto();
当然,您可以通过调整__call
调用的内容来自定义此行为.
And of course you can customize this behavior by tweaking what __call
invokes.
这篇关于从存储为类成员的字符串中调用类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!