Calling a static method of a class from another class width '$ this'

I have a problem's. I want to call a staticclass method from another class. The class name and method are created dynamically.

This is not so difficult to do:

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

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

BUT I want 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 this does not work unless I assign to a $this->classvariable $classand a $this->methodvariable $method. What is the problem?

+4
source share
2 answers

$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().

+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();
+1

All Articles