对于函数,我可以将函数名称分配给字符串变量,但是我如何为类方法做呢?
$func = array($this, 'to' . ucfirst($this->format));
$func(); // fails in PHP 5.3
这似乎可以工作:
$this->{"to{$this->format}"}();
但是对我来说太长了。我需要多次调用这个函数
一个选择是使用php的call_user_func_array()
;
例子:
call_user_func_array(array($this, 'to' . ucfirst($this->format)), array());
您还可以将self
关键字或类名与范围解析操作符一起使用。
例子:
$name = 'to' . ucfirst($this->format);
self::$name();
className::$name();
然而,你所发布的使用php的变量函数也是完全有效的:
$this->{"to{$this->format}"}();
call_user_func_array()
可能被认为比使用变量函数更具可读性,但是从我所读到的(像这里)来看,变量函数倾向于执行call_user_func_array()
。
变量函数太长是什么意思?
这不是一个真正的功能?为什么不使用函数的标准方法?
function func() {
$func = array($this, 'to' . ucfirst($this->format));
return $func;
}
然后用
输出func();
您可以使用call_user_func
:
class A
{
function thisIsAwesome()
{
return 'Hello';
}
}
$a = new A;
$awesome = 'IsAwesome';
echo call_user_func(array($a, 'this' . $awesome));
虽然它仍然很长。您可以编写自己的函数来完成:
function call_method($a, $b)
{
return $a->$b();
}
$a = new A;
$awesome = 'IsAwesome';
echo call_method($a, 'this' . $awesome);
这是一个更短的。