简体   繁体   中英

PHP - Dynamically reference object function

I'm not sure if this is possible, but i'm trying to dynamically call a function in my Test Class called Dropdown()

i am able to dynamically reference my public $Store; variable, by doing this.

$model=new Test;
$lol = 'Store';
echo $model->{$lol}; 

But when i try to call the function Dropdown() in my class, i get an error Property "Test.Dropdown()" is not defined.

$model=new Test;
$lol = 'Dropdown()';
echo $model->{$lol};

How would i dynamically call a function in my Test class?

Use $model->{$lol}() to call that method:

$className = 'Test'; //additional dynamic class call, if needed example for that too.

$class = new $className();
$method = 'Dropdown';
$class->{$method}();

You can use function call_user_func() or call_user_func_array() like this:

class Test {
    public function Dropdown($text) {
        echo($text);
    }
}

$class  = 'Test';           // class name
$method = 'Dropdown';       // only the method name, the '()' is part of the PHP syntax
$param  = "Hello world\n";  // parameter

call_user_func([$class, $method], $param);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM