1

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);

2 Answers2

0

No you can't do it directly, you'll have to manually extract the values from the array and pass them to the constructor, or change it so that it accepts an array as argument.

You might take a look at call_user_func_array but I don't think you can use it with a constructor as you need an instance of the object to call one of its methods.

Matteo Riva
  • 24,728
  • 12
  • 72
  • 104
  • This is what I've done in the past. Just pass an array to the function (as long as the function is allowed) – Matthew Dec 11 '10 at 14:42
  • Yes, since PHP 5.6, you can use argument unpacking using the [... operator](http://docs.php.net/manual/en/migration56.new-features.php#migration56.new-features.splat) – jgivoni Nov 14 '19 at 15:38
0

Note that the param list unpacking myfunc(*args) can be achieved with call_user_func_array():

$args = array("foo", "bar", "baz");

call_user_func_array("myfunc", $args);

For object methods you can use call_user_func_array(array($obj, "__construct"), $args). The deficiency here is the __constructor thus would be invoked twice, so should not do any funny things. Otherwise a specific init method is necessary.

Due to lack of named parameters an equivalent to myfunc(**args) does not exist in PHP. A common idiom is therefore to just pass the dict/array in, and let the function handle named params.

mario
  • 144,265
  • 20
  • 237
  • 291
  • In the comments of the call_user_func_array() there are some very good alternatives for doing that on functions and not on class only, such as the comment of Damin. – gaborous Apr 21 '15 at 14:26