在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