2

I have the following class:

class Foo {
  public function __construct($id, $name, $value) {}
}

I want to initialize this class using variables from an array, like:

$arr = array(1, 'some name', 'some value');
$fooObj = new Foo($arr);

It should work like a spread operator from ES6 in javascript:

callFunc(...arr);

Is this possible?

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
user99999
  • 1,994
  • 5
  • 24
  • 45

2 Answers2

4

In PHP >= 5.6.0, use argument unpacking as you show for JavaScipt with ...:

$fooObj = new Foo(...$arr);

For previous versions you can use call_user_func_array(), but unfortunately not to instantiate an object and pass to the constructor.

According to deceze you can use ReflectionClass::newInstanceArgs for instantiating your object:

$class  = new ReflectionClass('Foo');
$fooObj = $class->newInstanceArgs($arr);
Community
  • 1
  • 1
AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
  • 1
    The `call_user_func_array` equivalent for instantiating a class is [`ReflectionClass::newInstanceArgs`](http://php.net/manual/en/reflectionclass.newinstanceargs.php). – deceze Dec 22 '16 at 15:00
-2

The spread operator allows you to pass a list of parameters, and the function take these parameters as an array. In PHP you can use the variable argument list operator "...".

http://docs.php.net/manual/en/functions.arguments.php#functions.variable-arg-list

Example:

<?php
function sum(...$numbers) {
    $acc = 0;
    foreach ($numbers as $n) {
        $acc += $n;
    }
    return $acc;
}

echo sum(1, 2, 3, 4);
?>

Using your example:

class Foo {
  var $id;
  var $name;
  var $value;
  public function __construct(...$params) {
    $this->id=$params[0];
    $this->name=$params[1];
    $this->value=$params[2];
  }
}

Then call :

$var=new Foo(1, 'some name', 'some value');

In your case, you are trying to pass an array of parameters to a function. In this case you can omit the "..." operator and pass the elements:

class Foo {
  var $id;
  var $name;
  var $value;
  public function __construct($params) {
    $this->id=$params[0];
    $this->name=$params[1];
    $this->value=$params[2];
  }
}

Then call :

$arr = array(1, 'some name', 'some value');
$fooObj = new Foo($arr);
F.Igor
  • 4,119
  • 1
  • 18
  • 26