0
在对象内部,我得到一个字符串,并且必须知道当前对象中是否存在同名的方法。
我该怎么做?如何知道输入sting是特定类的方法名称?
在对象内部,我得到一个字符串,并且必须知道当前对象中是否存在同名的方法。
我该怎么做?如何知道输入sting是特定类的方法名称?
使用method_exists
。下面是一个例子:
$methodname = 'asdf';
if(method_exists($this, $methodname)) {
// call_user_func(array($this, $methodname)); See comments
$this->{$methodname}();
}
if (method_exists ($this, $methodName)) {
... exists
}
为什么'call_user_func'而不是'$ this - > {$ methodname}()'? – 2010-05-28 11:58:26
因为我没有想到你的建议。这肯定也会起作用,看起来它可能表现更好:http://www.php.net/manual/en/function.call-user-func.php#64415 – 2010-05-28 12:04:12