简体   繁体   中英

Call variable class with PHP without call_user_func

Is there a way to call a function in a class without using 'call_user_func' and without eval?

here is why I ask:

When I use 'call_user_func' I get the '$this not in context' error:

$this->id = $selectId['id'];
$file = 'score_' . $this->sid . '.php'; //the file with the class

if (@include_once($file)) { //including the file

    $scoreClass = 'Score_' . $this->id;
    call_user_func($scoreClass .'::selectData', $this->user_id);
}

I can overcome this 'not in context' error calling the function like this: but now my name is not variable.

$this->id = $selectId['id'];
$file = 'score_' . $this->sid . '.php'; //the file with the class

if (@include_once($file)) { //including the file

    $test = new Score_98673();
    $test->selectData($this->user_id);

}
call_user_func(array($score, 'selectData'), $this->user_id);

This is the correct syntax for the callable pseudotype.
http://php.net/manual/en/language.types.callable.php

You can also do this, BTW:

$method = 'selectData';
$score->$method($this->user_id);
if (@include_once($file)) { //including the file
    $scoreClass = 'Score_' . $this->id;
    $test = new $scoreClass();
    $test->selectData($this->user_id);
}

This is all you have to do. As you can use variable class names when using new .

The above fails as you call a non-static method (should throw some error) which uses $this .

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