在PHP5中,变量可以作为函数1进行评估,例如:
function myFunc() {
echo "whatever";
}
$callableFunction = 'myFunc';
$callableFunction(); // executes myFunc()
Run Code Online (Sandbox Code Playgroud)
是否有任何语法可以将对象成员函数分配给变量,例如:
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()
Run Code Online (Sandbox Code Playgroud)
有一种方法,但对于PHP 5.4及以上...
class MyClass {
function someCall() {
echo "yay";
}
}
$obj = new Myclass();
$ref = array($obj, 'someCall');
$ref();
Run Code Online (Sandbox Code Playgroud)
嗯..实际上它也适用于静态,只需使用名称引用..
class MyClass {
static function someCall2() {
echo "yay2";
}
}
$ref = array('MyClass', 'someCall2');
$ref();
Run Code Online (Sandbox Code Playgroud)
对于非静态的,这种表示法也适用.它创建了一个类的临时实例.所以,这就是你需要的,只需要你需要php 5.4及以上版本)