Of course you can do it without eval()
. PHP will take either a string containing the class name or the literal as an argument to the new
operator.
$duck = new $input; // parentheses are optional
echo $duck->func();
Question
Example:
<?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
Is there any way I can do this without using eval()
?
Solution
Of course you can do it without eval()
. PHP will take either a string containing the class name or the literal as an argument to the new
operator.
$duck = new $input; // parentheses are optional
echo $duck->func();
OTHER TIPS
Yes you can by storing the class name into a string, for example :
$input = "a";
$duck = new $a();
if(is_callable($duck',"func")){
$duck->func();
}
would work