Reputation: 541
The code:
final class SimpleEventManager {
private $listeners = array();
public function listen($event, $callable) {
$this->listeners[$event][] = $callable;
}
public function fire($event, array $arguments = array()) {
foreach ($this->listeners[$event] as $listener) {
call_user_func_array($listener, $arguments);
}
}
}
$manager = new SimpleEventManager;
$manager->listen('sql', function($sql) {
$sql .= " order by username desc";
});
$sql = "select * from users";
$manager->fire('sql', array($sql));
var_dump($sql); // is: select * from users
// want: select * from users order by username desc
So basically i want my event listeners to be able to modify the arguments that come in. I've tried doing things like array &$arguments = array()
but then I'm getting the Cannot pass parameter 2 by reference
error.
Does anyone know how I can solve this?
Upvotes: 2
Views: 1529
Reputation: 324750
You can't pass it by reference because only variable may be passed by reference. The literal array($sql)
is clearly not a variable.
That said, this isn't the problem.
In fact, there's a lot of problems, mostly because of $sql
being "copied" so many times:
array($sql)
fire()
(due to not being passed by reference)First of all you need to define your array as a variable, such as $arr = array(&$sql);
Then keep your current "fix" of passing &$arguments
by reference.
Finally, adjust your anonymous function to function(&$sql)
to also work by reference.
All in all, this could be made a lot easier if your code weren't so convoluted ;)
Upvotes: 2