在PHP5中,变量可以被评估为功能1如:PHP - 你能分配一个成员函数给变量吗?
function myFunc() {
echo "whatever";
}
$callableFunction = 'myFunc';
$callableFunction(); // executes myFunc()
是否有诸如分配对象的成员函数的变量任何语法:
class MyClass {
function someCall() {
echo "yay";
}
}
$class = new MyClass();
// what I would like:
$assignedFunction = $class->someCall; // but I tried and it returns an error
$memberFunc = 'someCall';
$class->$memberFunc(); // I know this is valid, but I want a single variable to be able to be used to call different functions - I don't want to have to know whether it is part of a class or not.
// my current implementation because I don't know how to do it with anonymous functions:
$assignedFunction = function() { return $class->someCall(); } // <- seems lengthy; would be more efficient if I can just assign $class->someCall to the variable somehow?
$assignedFunction(); // I would like this to execute $class->someCall()
是的,你可以使用php的call_user_function()方法。 – 2014-10-18 03:56:12
call_user_function()不符合我的要求..我仍然需要知道使用call_user_function()调用哪个类和哪个函数。我想编写调用''customFunc()'''调用,以便能够在运行时调用任意函数,而无需事先知道它是内置函数,用户函数,类静态函数还是类对象成员函数。 – PressingOnAlways 2014-10-18 04:09:13