Passing and expecting parameters with …$things

selectThis is one of those blog posts I wrote really to note things down for myself. So if you are a highly skilled and cutting edge PHP expert, you might skip over that piece of noob talk. But if you were confused about that never-seen-before code with three dots in front of a parameter name like …$random, and you never could tell, what the developer wanted to tell you, you could learn from my research.

In the wake of the doctrine DBAL transition I stumbled often upon a strange syntax like protected function someFunction(...$params) {}  and someClass->someOtherFunction(...$moreParams)  . And I had absolutely no clue, what’s happening here with this three dots. So I did some reading, a lot of thinking, a little bit more of reading, a lot of discussions with Anja and finally some lines of code to play around.

First steps with var_dump()

First some „normal“ stuff. var_dump($testArray);  results (as expected) into

What happens, if I call var_dump(...$testArray);  ? I had no clue, if var_dump would be able to handle that, but luckily it works.

Conclusion: The three dots in front of the $testArray transformed the array on the fly into a comma separated list. Nice. I can’t imagine much use cases for that right now, but … nice.

Try it with some own function

Next I wanted to see what happens, if I have a function with these dots in the parameter declaration.

Not that high sophisticated, but should do the trick. Fire in the hole!

Conclusion: The three dots in the parameter declaration of the function takes care that an infinite amount of parameters would be merged together as a single array.

What can we break next?

Just because I was curious what would happen, I invented another function.

I guess you could imagine, what would be the results ob the three different calls from above. The call with the array resulted in a couple of warnings, because I only provided one out of three arguments. The other two calls (one with …$testArray and one with the comma separated list) ignored the forth parameter and dumped only the first three.


I am not entirely certain of the use cases for these constructs. I saw one pretty fine example, that showed the usefulness pretty impressive by reducing the amount of code by 90%. Mostly by removing if statements like (if count($parameter) == 2) than call the function with two paramters, if count is N, than call the same function with N arguments. On the other hand it tends to be a little bit obscure on reading. But to reduce this effect on myself, I wrote this very blog post.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert.