简体   繁体   English

从另一个类'$ this'调用类的静态方法

[英]Call a static method of class from another class width '$this'

I've got some problem. 我有一些问题。 I want to call static method of class from another class. 我想从另一个类调用类的static方法。 Class name and method are created dynamically. 类名称和方法是动态创建的。

It's not really hard to do like: 做起来并不难:

$class = 'className';
$method = 'method';

$data = $class::$method();

BUT, i want to to do it like this 但是,我想这样做

class abc {
    static public function action() {
        //some code
    }
}

class xyz {
    protected $method = 'action';
    protected $class = 'abc';

    public function test(){
        $data = $this->class::$this->method();
    }
}

And it doesn't work if i don't assign $this->class to a $class variable, and $this->method to a $method variable. 如果我不将$this->class赋值给$this->class $class变量,并将$this->method分配给$method变量,它就不起作用。 What's the problem? 有什么问题?

The object syntax $this->class , $this->method makes it ambiguous to the parser when combined with :: in a static call. 对象语法$this->class$this->method在静态调用中与::结合时使解析器不明确。 I've tried every combination of variable functions/string interpolation such as {$this->class}::{$this->method}() , etc... with no success. 我已经尝试了变量函数/字符串插值的每个组合,例如{$this->class}::{$this->method}()等......但没有成功。 So assigning to a local variable is the only way, or call like this: 因此,分配给局部变量是唯一的方法,或者像这样调用:

$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}");

If you need to pass arguments use call_user_func_array() . 如果需要传递参数,请使用call_user_func_array()

In PHP 7.0 you can use the code like this: 在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();

For PHP 5.6 and lower you can use the call_user_func function: 对于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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM