Page 1 of 1

dynamically instantiating a class

Posted: Wed Mar 16, 2005 3:15 pm
by sonofslim
i'm attempting to dynamically instantiate some classes, with code resembling the below. i've stripped out everything that's not relevant to the problem, so it may look like i'm trying to do things the hard way, but i've got my reasons for it. anyway, here's what i started with:

Code: Select all

function loadClass($name)
{
	$args = func_get_args();
	$args = "'".implode("', '", array_slice($args, 1))."'";
	$newClass = new $name($args);
	return $newClass;
}
for example: i want to instantiate a class called className that expects 2 arguments in its constructor, like so:

Code: Select all

$newObject = $existingClass->loadClass('className', 'arg1', 'arg2');
but my various classes to be loaded have differing numbers of arguments, which is why i can't just say: $newObject = new $name($arg1, $arg2).

the code above fails because it just takes all of the arguments (minus the 1st, which is the name of the class to be dynamically instantiated) and puts them into one string, which is passed as one argument.

i've also tried slicing off the first element of my arguments array and passing the array, but that just loads an array into my first argument.

so, without rewriting all of my classes to accept arrays instead of lists, is there a way to accept a number of arguments that is unknown beforehand and pass them on to a second function/class?

thanks for any insight you may have...


feyd | Please use

Code: Select all

and

Code: Select all

tags where approriate when posting code. Read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url][/color]

Posted: Wed Mar 16, 2005 4:13 pm
by feyd
look into using eval(), or specialized creation handlers, or better yet use a factory pattern.

By the way, if you are using php4, you just asked php to copy the new object at least two times.

Posted: Wed Mar 16, 2005 7:14 pm
by timvw
http://be2.php.net/manual/en/functions. ... e-arg-list and the functions mentioned there......

Posted: Thu Mar 17, 2005 2:04 pm
by sonofslim
thanks for the tips -- i'm new to the design pattern thing. i'd appreciate any feedback on the solution i came up with; always looking for ways to improve!

Code: Select all

class moduleFactory
{
	function &createModule($module)
	{
		$args = func_get_args();
		for($i = 1; $i < sizeof($args); $i++)
		{
			if(!empty($arglist)) { $arglist .= ','; }
			$arglist .= "'".$args[$i]."'";
		}
		return eval('return new '.$module.'('.$arglist.');');
	}
}

// to instantiate a new class, pass the name of the class
// followed by any arguments for the constructor

class foo extends module
{
     function foo($arg1, $arg2) { }
}

$newFoo =& moduleFactory::createModule('foo', 'bar', 'blah');
how's that look?