-1

Below is a function which we can find in core Magento 2 code.

protected function createObject($type, $args)
{
    return new $type(...array_values($args));
}

This function is instantiating $type (which is a string parameter) with the arguments $args (which is an array parameter).

What I am not getting is those 3 dots (...). Is this a valid syntax at all ? I never found such an object instantiation before !!

I tried to remove those dots and try to load a page. It gives fatal errors. So it seems that, those three dots are not accidentally come over there.

It seems like that code won't work for php-5.3 or lower versions. So it is something new which I couldn't find anywhere.

Rajeev K Tomy
  • 2,206
  • 1
  • 18
  • 35

2 Answers2

2

It is a variable-length argument lists. They are new to PHP 5.6.x. This example is from the PHP manual:

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

echo sum(1, 2, 3, 4);
?>
Tigger
  • 8,980
  • 5
  • 36
  • 40
1

It's a great way to use array as function parameter or argument list. Actually, It's replacement for the func_get_args() function. Variable-length argument lists

Ataur Rahman
  • 1,671
  • 14
  • 12