Bryant Makes Programs
Bryant Makes Programs

Reputation: 1704

Reference static class method given class name as string in PHP5.5

I have a variable that holds a class name.

public $modelClass = 'common\models\Notecard';

That class has a static method.

public static function do_something() { ... }

Given this information, I would like to call the static function. For non-static functions, I can do the following:

$model_name = $this->modelClass;
$model = new $model_name();
$model->do_something_else();

Upvotes: 0

Views: 359

Answers (2)

Kayson
Kayson

Reputation: 405

You can use $model_name::do_something_else().

class foo {
    public static function bar() {
        echo "Called bar";
    }
}

$fname = "foo";
$fname::bar();

Outputs Called bar

Works on php7.

Upvotes: 0

robske_110
robske_110

Reputation: 343

Yes, that is pretty easy: You can either just call the function from your instance e.g.

$model_name = $this->modelClass;
$model = new $model_name();
$model::do_something();

or using call_user_func()

call_user_func([$modelClass, 'do_something']);

Upvotes: 2

Related Questions