Creating objects with eval()

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
smudge
Forum Contributor
Posts: 151
Joined: Sun May 20, 2007 12:13 pm

Creating objects with eval()

Post by smudge »

Hello, I have a function which include()s a class then returns an instance of it:

Code: Select all

function loadClass($file,$name,$opts=array()){
  include $file;
  return eval("new {$name}(".implode(',',$opts).")");
}
But if I try loadClass('default.php','DefaultController'), I get syntax errors for an unexpected $end, and an unexpected T_DEFAULT (expecting ')').

This leads to 2 questions, how do I fix the errors? and is there a better way?
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

If you're running PHP 5, Reflection is the better way to head.

You may want to check if the file has already been loaded with get_included_files() and in_array().

It's generally suggested to avoid eval() at all costs as the dangers of the function often outweigh the experience and actual needs of the programmer calling them. If the classes had an initialization method, not unlike the constructor's purpose, you could avoid eval() entirely using

Code: Select all

$foo =& new $name;
call_user_func_array(array($foo, 'initialize'), $opts);
return $foo;
smudge
Forum Contributor
Posts: 151
Joined: Sun May 20, 2007 12:13 pm

Post by smudge »

Thanks, I will try that, and it seems to be the best solution.
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post by Chris Corbyn »

feyd wrote:If the classes had an initialization method, not unlike the constructor's purpose, you could avoid eval() entirely using

Code: Select all

$foo =& new $name;
call_user_func_array(array($foo, 'initialize'), $opts);
return $foo;
Yay for static factory methods! :) If you created your object via a basic factory:

Code: Select all

class Foo {
  function Foo($arg1, $arg2, $arg3) {
    //
  }
  function &newInstance($arg1, $arg2, $arg3) {
    $instance =& new Foo($arg1, $arg2, $arg3);
    return $instance;
  }
}
Then you could make use of call_user_func_array() directly to create the object:

Code: Select all

$obj =& call_user_func_array(array("Foo", "newInstance"), $argList);
Post Reply