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?

1
  • 1
    @Super Nope, the reverse is being asked here. Commented Dec 22, 2016 at 14:59

2 Answers 2

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

1 Comment

The call_user_func_array equivalent for instantiating a class is ReflectionClass::newInstanceArgs.
-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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.