This function can take the place of the new keyword for instantiating classes. Currently only primitive types can be passed as argument parameters. I was trying to figure out a way to pass arrays in the argument list using func_get_args() and eval() but can't think of way to produce the constructor argument list.

define( 'SYSTEMROOT', 'path/to/documentroot' );
/**
 * PHP 4 class autoloading function
 * @param $classname The name of the class to instantiate
 * @param $path The path to the file containing the class, dot separated a la Java
 * @param $params Array of parameters to pass to the class constructor. Primitive types only
 * @return object
*/
function &cl( $classname, $path, $params = null )
{
	if( !class_exists( $classname ))
	{
		require_once( SYSTEMROOT . '/' . str_replace( '.', '/', $path ) . '.php' );
	}
	if( $params != null )
	{
		$params = implode( ',', $params );
		eval( "\$object =& new $classname( $params );" );
		return $object;
	}
	return new $classname;
}

$foo =& cl( 'mySqlDataLayer', 'classes.database.mysql', array( 1, 2 ));

    I was going to say [man]call_user_func_array[/man] but there doesn't seem to be a way of dynamically instantiating classes with that. I'm sure there must be a function for doing this though, just can't seem to find it 🙁
    For portability '/' could be replaced with DIRECTORY_SEPERATOR
    Also, the parameter implode will break on strings, the following might be safer.

    $params = '"' . implode( '","', $params ) . '"';

    [edit]There is a more comprehensive reflection API in PHP4, I remember reading it in a book I have at home recently. I will try to remember to look it up this evening[/code]

      Good tips there - I had sort of envisioned only ever using an array to make the parameter list but fair point, using strings would be good too 🙂

        Write a Reply...