2012-11-25 69 views
0

我在调用名称存储在数组中的函数时遇到问题。Array中的函数名称

class tempClass { 
    function someFunction() { 
     $tempArray = array('functionName' => 'tempFunction'); 
     $tempArray['functionName'](); 
    } 

    function tempFunction() { 
     echo "inside function"; 
    } 
} 

它给了我一个错误:

"Fatal error: Call to undefined function tempFunction() in /..... line..". 

行号是函数被调用的行,$tempArray['functionName']();

但是如果叫method_exists(),这表明,该方法是存在。这很混乱。任何人都可以请帮我吗?谢谢。

+0

可能存在[可以在PHP数组中存储函数吗?](http://stackoverflow.com/questions/1499862/can-you-store-a-function-in-a-php-array) –

回答

2

使用call_user_func(),像这样:

call_user_func($tempArray['functionName']); 

UPDATE:
正如你希望从类中调用类的方法,请使用以下代替:

call_user_func(array($this, $tempArray['functionName'])); 

看工作demo

+0

我得到这个错误“警告:call_user_func()期望参数1是一个有效的回调函数'tempFunction'未找到或无效的函数名称....” –

+1

与原始尝试相同的问题:您缺少范围。 – arkascha

+0

是的,你是对的,我是多么愚蠢。我用$ this - > $ tempArray ['functionName']();它的工作。非常感谢你们。 –

2

那么你问,如果方法d存在于类或对象内部,但是你没有这个范围就调用它。这将无法正常工作......

试试这个:

call_user_method($tempArray['functionName'],$this); 

刚才看到call_user_method()折旧。使用call_user_func()作为Nelson的回答。

+0

它没有与上述cmd一起工作,但我只是将范围添加到调用函数。谢谢。 –

+0

这个答案不起作用,错误可以在这里看到http://codepad.org/CIT7IDhT – Nelson

+0

@Nelson:那是真的,对不起。我纠正了答案,但Nelsons的回答更好:只是看到'call_user_mothod'已折旧!对困惑感到抱歉。 – arkascha