标签:php
参见英文答案 > php call class function by string name 5个
在PHP5中,变量可以被评估为functions1,例如:
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(); } // someCall to the variable somehow?
$assignedFunction(); // I would like this to execute $class->someCall()
解决方法:
有一种方法,但对于PHP 5.4及以上…
class MyClass {
function someCall() {
echo "yay";
}
}
$obj = new Myclass();
$ref = array($obj, 'someCall');
$ref();
嗯..实际上它也适用于静态,只需使用名称引用..
class MyClass {
static function someCall2() {
echo "yay2";
}
}
$ref = array('MyClass', 'someCall2');
$ref();
对于非静态的,这种表示法也适用.它创建了一个类的临时实例.所以,这就是你需要的,只需要你需要php 5.4及以上版本)
标签:php
来源: https://codeday.me/bug/20190528/1172512.html