4

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?

1
  • 4
    $this always point at the current object - the one that the method is executing in. you can't use $this and magically have it become some other object's "this". And even if you could do $this->$class->action(), $class is just a string. it's not an object, and doesn't point at an instance of an object, so you can't use to execute a method in an object, even if that string is the name of some object. the only thing you could use it for is calling a STATIC method of the class it represents.
    – Marc B
    Commented Mar 8, 2016 at 19:43

2 Answers 2

1

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

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.