Yossi
Yossi

Reputation: 1056

PHP - Using a Double colon with a class varible

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?

Upvotes: 0

Views: 399

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 79014

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(''));
}

Upvotes: 1

Machavity
Machavity

Reputation: 31644

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

Upvotes: 2

Related Questions