![](/img/trans.png)
[英]PHP: is it possible to call a static class method from another static class?
[英]Call a static method of class from another class width '$this'
我有一些问题。 我想从另一个类调用类的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
赋值给$this->class
$class
变量,并将$this->method
分配给$method
变量,它就不起作用。 有什么问题?
对象语法$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() 。
在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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.