【问题标题】:Call a static method of class from another class width '$this'从另一个类宽度 '$this' 调用类的静态方法
【发布时间】:2016-06-22 22:36:06
【问题描述】:

我遇到了一些问题。 我想从另一个类调用类的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 变量,它就不起作用。 有什么问题?

【问题讨论】:

  • $this 总是指向当前对象——方法正在执行的那个。你不能使用$this 并神奇地让它变成其他对象的“this”。即使你可以做到$this->$class->action()$class 也只是一个字符串。它不是对象,也不指向对象的实例,因此即使该字符串是某个对象的名称,您也不能使用它来执行对象中的方法。您唯一可以使用它的就是调用它所代表的类的 STATIC 方法。

标签: php class methods static


【解决方案1】:

在 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();

【讨论】:

    【解决方案2】:

    对象语法$this-&gt;class$this-&gt;method 在与静态调用中的:: 结合使用时会使解析器产生歧义。我已经尝试了变量函数/字符串插值的每种组合,例如{$this-&gt;class}::{$this-&gt;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()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-10-18
      • 2016-06-26
      • 1970-01-01
      • 2015-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多