例:
<?php
class a{
public function func(){
return "a";
}
}
class b{
public function func(){
return "b";
}
}
$input = "a"; // Would come from user input
eval('$duck = new '.$input.'();');
$duck->func(); // Returns a in this case
Run Code Online (Sandbox Code Playgroud)
有没有办法我可以不使用eval()?
当然你可以不用eval().PHP将把包含类名的字符串或文字作为new运算符的参数.
$duck = new $input; // parentheses are optional
echo $duck->func();
Run Code Online (Sandbox Code Playgroud)