我想将自定义事件处理程序添加到对象的方法中。
我有一个带有方法的类。
class Post {
public function Add($title) {
// beforeAdd event should be called here
echo 'Post "' . $title . '" added.';
return;
}
}
我想向方法 Add
添加一个事件,并将方法的参数传递给事件处理程序。
function AddEventHandler($event, $handler){
// What should this function do?
}
$handler = function($title){
return strtoupper($title);
}
AddEventHandler('beforeAdd', $handler);
有没有可能做这样的事情?希望我的问题很清楚。
最佳答案
使用这里定义的函数应该很容易 http://www.php.net/manual/en/book.funchand.php
特别是你应该保留一个处理程序数组(或者数组数组,如果你想为同一个事件使用多个处理程序)然后做一些类似的事情
function AddEventHandler($event, $handler){
$handlerArray[$event] = $handler;
}
或
function AddEventHandler($event, $handler){
$handlerArray[$event][] = $handler;
}
在多个处理程序的情况下。
然后调用处理程序只是调用“call_user_func”的问题(如果需要多个处理程序,最终在一个循环中)
关于PHP:如何实现事件处理器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3896347/