I struggled a few hours on writing a simple Generic factory method for dynamic object factoring. I initially went for call_user_func_array() to create the object but that obviously didn't work. An anonymous function was what I needed. Here's the result (PHP5):
<?php
class Factory
{
public static function Generic($filename, $base, $derived, $args = array())
{
if(file_exists($filename))
{
include_once $filename;
if(class_exists($derived))
{
$arglist = array();
for($i = 0, $n = count($args); $i < $n; $i++)
$arglist[] = '$args['.$i.']';
$arglist = implode(',',$arglist);
$new_class = create_function('$name, $args', 'return new $name('.$arglist.');');
return $new_class($derived, $args);
}
else
throw new Exception("Definition file ($filename) did not contain definition for the $base class <code>$derived</code>");
}
else
throw new Exception("Definition file ($filename) for the $base class <code>$derived</code> was not found");
}
}
function createCat($name, $scary_eyes = FALSE, $whiskers = TRUE)
{
$path = PATH_ANIMALS.'/'.$name.'.php';
$base = 'Cat';
$derived = $name.$base;
$args = array($scary_eyes, $whiskers);
return Factory::Generic($path, $base, $derived, $args);
}
$cat = createCat('Meow', TRUE);
?>