Reputation: 2387
I hope this question is not duplicated.
I have the following event defined:
Event::listen('test', function(array $data){
dd($data);
});
When I attempt to fire it, I receive the below exception:
event('test', [
'foo' => 'bar',
'asdf' => 'ghjk',
]);
TypeError:
Argument 1 passed to {closure}() must be of the type array, object given
However if I execute it the following way, problem does not occur:
event('test', [[
'foo' => 'bar',
'asdf' => 'ghjk',
]]);
Question: if I want to pass a strict array to the listener closure, is there a way to avoid the wrapping of my var in another array?
Upvotes: 1
Views: 1663
Reputation: 3764
After digging into the framework a bit I think I have found the "problem".
The array you are passing into your listener is supposed to be the arguments of the callback. ie)
Event::listen('test', function($foo, $bar, $baz) {
dd($foo, $bar, $baz);
});
event('test', ['foo', 'bar', 'baz']);
When you pass an array to the event() helper it will ultimately call makeListener in Illuminate\Events\Dispatcher to execute your closure. And in that method it calls your listener as follows:
return $listener(...array_values($payload));
So the reason why:
event('test', [[
'foo' => 'bar',
'asdf' => 'ghjk',
]]);
Works, is because:
...array_values([[
'foo' => 'bar',
'asdf' => 'ghjk',
]])
is simply ['foo' => 'bar', 'asdf' => 'ghjk']
Hope that helps! One of those things that is just about finding the right documentation!
So to answer your ultimate question:
"Question: if I want to pass a strict array to the listener closure, is there a way to avoid the wrapping of my var in another array?"
No :(
Upvotes: 2