0

I'm trying to call a static function with a varible name from a class.

The desired outcome:

class Controller extends Controller {
    public $model = 'ModelName';
    public function index() {
        $woot = $this->model::find('');
        var_dump($woot);
    }
}

This works:

$class = 'ClassName';
$object = $class::find($parameters);

This works too:

$class = new Model();
$object = $class::find($params);

I am trying to define the new class name inside the current class, and call find as a static function from the current model. Any ideas how it's possible, without creating a new object, using __set, or declaring a local variable in the function?

Machavity
  • 30,841
  • 27
  • 92
  • 100
Yossi
  • 1,056
  • 2
  • 13
  • 22

2 Answers2

2

You can't do that actually. Within a class instance you cannot use $this->var to reference another class. You can, however, assign it to another local variable and have that work

public function index() {
    $var = $this->model;
    $woot = $var::find('');
    var_dump($woot);
}
Machavity
  • 30,841
  • 27
  • 92
  • 100
1

I would go with Machavity's method, but you can use call_user_func() or call_user_func_array():

public function index() {
    $woot = call_user_func_array(array($this->model, 'find'), array(''));
}
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87