Instantiating a new PHP class with one or many arguments
I have this fetch function:
public static function fetch($class, $key)
{
try
{
$obj = new $class($key开发者_高级运维);
}
catch(Exception $e)
{
return false;
}
return $obj;
}
It creates a new instance by calling that class's constructor and passing in the key. Now, how would I make it so I can pass in an array of arguments in $key, and have it like:
$obj = new $class($key[0], $key[1]...);
So that it works for one or more keys?
Hopefully that was clear enough.
Using PHP 5
This is an interesting question. If it wasn't a constructor function you were trying to give dynamic arguments to, then normally you could use call_user_func_array(). However, since the new
operator is involved, there doesn't seem to be an elegant way to do this.
Reflection seems to be the consensus from what I could find. The following snippet is taken from the user comments on call_user_func_array(), and illustrates the usage quite nicely:
<?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');
?>
To shorten it up for your case, you can use:
$reflectionObject = new ReflectionClass($class);
$obj = $reflectionObject->newInstanceArgs($key);
Use reflection:
$classReflection = new ReflectionClass($class);
$obj = $classReflection->newInstanceArgs($key);
My library solves this this:
// Returns a new instance of a `$classNameOrObj`.
function fuNew($classNameOrObj, $constructionParams = array()) {
$class = new ReflectionClass($classNameOrObj);
if (empty($constructionParams)) { return $class->newInstance(); }
return $class->newInstanceArgs($constructionParams); }
The empty()
test is required because newInstanceArgs()
will complain if you give it an empty array, stupidly.
What does the constructor of the class look like? Does it accept an arbitrary number of arguments? It might be better to accept an array of keys instead of a list of key arguments.
call_user_func_array
could probably do what you want:
$obj = new $object_class();
call_user_func_array(array($obj, '__construct'), $args);
Note that this calls the constructor twice, which could have negative side effects.
精彩评论