4

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()?

j0k
  • 22,600
  • 28
  • 79
  • 90

2 Answers2

8

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();
Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
  • 2
    I've been coding PHP for almost a year now, and PHP OOP for about a month. I never expected it to be that easy. –  Dec 07 '12 at 07:03
1

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

artragis
  • 3,677
  • 1
  • 18
  • 30