2

I use spread syntax in JavaScript, but what are they used for in PHP? In all cases which I've tried it acts just like a usual array. Is there some good use for it which I didn't find?

(I know how it works, just asking for a useful example, where it is more useful than array)

Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Jax-p
  • 7,225
  • 4
  • 28
  • 58
  • @zack6849 Found this topic but it didn't fill my expectations. It looks useless. – Jax-p Apr 27 '18 at 17:55
  • 1
    It looks to me like whatever a js spread operator is is not equivalent in php, it's a [variable length argument list](http://php.net/manual/en/functions.arguments.php#functions.variable-arg-list) – Zachary Craig Apr 27 '18 at 17:56
  • @zack6849 Well in function (...$var) $var comes like a array of arguments. I would still rather use array. Like ([value, value, value]) – Jax-p Apr 27 '18 at 17:59
  • 1
    i mean, i guess, it's just a feature, nobody is going to force you to sue it a specific way – Zachary Craig Apr 27 '18 at 18:00
  • I agree, I was just looking for some useful features with it, in JS it looks more useful for me. – Jax-p Apr 27 '18 at 18:01

1 Answers1

4

The spread operator (...) transforms an array (or generically a Traversable) into an argument list, and vice-versa. If you're looking for anything more fancy than this, you're out of luck: the Javascript implementation is simply more powerful, in that it also transforms object expressions into key-value pairs, and vice-versa.

How might you use this? Well, consult the original RFC that defined it for some practical examples:

  • More performant than call_user_func_array
  • Extending variadic functions: forwarding
  • Partial application: multiple unpacks

I personally use it because of that first point. As mentioned in the RFC:

The ... argument unpacking syntax is about 3.5 to 4 times faster than call_user_func_args. This solves the performance issue. Benchmark code and results.

You might also ask why PHP didn't implement the object unpacking, like Javascript. That too is answered in the RFC:

In order to ensure forward-compatibility with named arguments the unpacking operator does not support string keys. If a string key is encountered during unpacking a recoverable error is thrown. If the error is ignored using a custom error handler, no further arguments will be unpacked but the call still happens.

I personally find this to be a trap, which is why I abstained from voting on this RFC.

bishop
  • 37,830
  • 11
  • 104
  • 139