我遇到了一些问题。我想从另一个类调用static
类的方法。类名和方法是动态创建的。
这样并不难做到:
$class = 'className';
$method = 'method';
$data = $class::$method();
但是,我想这样做
class abc {
static public function action() {
//some code
}
}
class xyz {
protected $method = 'action';
protected $class = 'abc';
public function test(){
$data = $this->class::$this->method();
}
}
如果我不将$this->class
分配给$class
变量,$this->method
分配给$method
变量,则它不起作用。怎么了?
在 PHP 7.0 中,你可以像这样使用代码:
<?php
class abc {
static public function action() {
return "Hey";
}
}
class xyz {
protected $method = 'action';
protected $class = 'abc';
public function test(){
$data = $this->class::{$this->method}();
echo $data;
}
}
$xyz = new xyz();
$xyz->test();
对于 PHP 5.6 及更低版本,您可以使用 call_user_func 函数:
<?php
class abc {
static public function action() {
return "Hey";
}
}
class xyz {
protected $method = 'action';
protected $class = 'abc';
public function test(){
$data = call_user_func([
$this->class,
$this->method
]);
echo $data;
}
}
$xyz = new xyz();
$xyz->test();
对象语法$this->class
,$this->method
在静态调用中与 ::
结合使用时,解析器不明确。 我已经尝试了变量函数/字符串插值的各种组合,例如{$this->class}::{$this->method}()
等......没有成功。 因此,分配给局部变量是唯一的方法,或者像这样调用:
$data = call_user_func(array($this->class, $this->method));
$data = call_user_func([$this->class, $this->method]);
$data = call_user_func("{$this->class}::{$this->method}");
如果需要传递参数,请使用 call_user_func_array()。