1

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

4 Answers 4

8

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); 
Sign up to request clarification or add additional context in comments.

Comments

5

Use reflection:

$classReflection = new ReflectionClass($class); $obj = $classReflection->newInstanceArgs($key); 

Comments

2

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.

Comments

0

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.

2 Comments

Also note this won't work for PHP4 code which uses the name of the class as the constructor's name instead of __construct.
Depends on the class, some are __construct($key) some are __construct($key1, $key2)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.