Page 1 of 1
Creating objects with eval()
Posted: Mon Aug 20, 2007 10:38 am
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?
Posted: Mon Aug 20, 2007 10:46 am
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;
Posted: Mon Aug 20, 2007 12:50 pm
by smudge
Thanks, I will try that, and it seems to be the best solution.
Posted: Mon Aug 20, 2007 1:50 pm
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);