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!
function load($class)
{
//If $class is an array assume the first index is the class name.
if(is_array($class))
{
$class_name = array_shift($class);
}
$class_path = str_replace('_', '/', $class_name);
if(file_exists($_SERVER['DOCUMENT_ROOT'].'/'.$class_path.'.php'))
{
include_once($_SERVER['DOCUMENT_ROOT'].'/'.$class_path.'.php')
{
//If $class was an array pass the arguments here as
// $arg1, $arg2, $arg3 and so forth.
return new $class_name;
}
}
}
As I've commented above if $class is an array shift the first element off as the name. Then pass the rest of the array as arguments into the classes constructor as $arg0, $arg1, $arg2 and so forth.
<?php
// arguments you wish to pass to constructor of new object
$args = array('a', 'b');
// class name of new object
$className = 'myCommand';
// make a reflection object
$reflectionObj = new ReflectionClass($className);
// use Reflection to create a new instance, using the $args
$command = $reflectionObj->newInstanceArgs($args);
// this is the same as: new myCommand('a', 'b', 'c');
?>
I've tried a couple of ways to make this work for PHP 4. But to no avail. I've read the comments. eval() won't work. No way to adequately sanitize user input. Well. Looks like no wysiwyg method for this load object unless my constructors don't except parms. HAHA!