sauvox
sauvox

Reputation: 41

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. 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. What's the problem?

Upvotes: 4

Views: 1342

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 78994

The object syntax $this->class, $this->method makes it ambiguous to the parser when combined with :: in a static call. I've tried every combination of variable functions/string interpolation such as {$this->class}::{$this->method}(), etc... with no success. 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().

Upvotes: 1

aiko
aiko

Reputation: 432

In PHP 7.0 you can use the code like this:

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

Upvotes: 1

Related Questions