In Python, you can pack and unpack arguments like so:
def myfunction(arg1, arg2, arg3):
pass
mydict = dict(arg1='foo', arg2='bar', arg3='baz')
myfunction(**mydict)
mylist = ['foo', 'bar', 'baz']
myfunction(*mylist)
Now, is there something similar in PHP? I have a class that is passed to a function, along with an associative array extracted from a database record. I want to create an instance of the class, which accepts arguments that are named the same as the keys in the array. Can it be done?
EDIT
Ok, so I definitely didn't formulate my question correctly. I wanted to instantiate a new class dynamically when I know neither the class name, nor the number of arguments beforehand.
I've found the Answer though:
http://php.net/manual/en/book.reflection.php
Here's the solution:
class MyClass {
public function __construct($var1, $var2, $var3) {
echo "$var1\n";
echo "$var2\n";
echo "$var3\n";
}
}
$reflector = new ReflectionClass('MyClass');
$args = array('var1'=>'foo', 'var2'=>'baz', 'var3'=>'bar');
$instance = $reflector->newInstanceArgs($args);