Page 1 of 1

Dynamic argument passing question

Posted: Sun Apr 15, 2007 6:30 pm
by neophyte
Working with PHP 4, I'm trying to pass arguments dynamically. Here's my code.

Code: Select all

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.

Can this be achieved?

Posted: Sun Apr 15, 2007 7:18 pm
by aaronhall
I'm not sure if it will work for object constructors, but you might give call_user_func_array() a shot

Posted: Sun Apr 15, 2007 7:24 pm
by aaronhall
If you're using PHP5, you can use the reflection API instead (code is from the call_user_func_array() comments):

Code: Select all

<?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');
?>
If not:

Code: Select all

$obj = call_user_func_array(array($className, '__construct'), $args);

Posted: Sun Apr 15, 2007 10:20 pm
by neophyte

Code: Select all

$obj = call_user_func_array(array($className, '__construct'), $args);
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!

Posted: Sun Apr 15, 2007 10:29 pm
by aaronhall
You might find something in the comments for call_user_func_array() (where a lot of my suggestions came from)

Posted: Sun Apr 15, 2007 10:57 pm
by neophyte
Been there read that. Didn't see anything. Looks like the only way to do it in 4 is eval(). Bummer. |P

Posted: Sun Apr 15, 2007 11:04 pm
by aaronhall
:? PHP4 makes it hard to develop a well-rounded OO app... maybe time to upgrade if you can? :wink:

Posted: Sun Apr 15, 2007 11:37 pm
by neophyte
I wish. Audience won't allow it (IMHO). Its the next version of my Gallery ware. Too many people still running 4.