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