• 0
  • 0

PHP钩子实现演示代码

2019-12-06 62 0 admin 所属分类:PHP 记录
<?php
class Ball {
    public function down() {
        //注册事件
        echo "ball is downing ";
        Hook::add("man");
        Hook::add("Women");
    }

    public function do() {
        Hook::exec();
    }
}

// 钩子的定义
class Hook {
    private $hooklist = null;
    // 添加
    public function add($people) {
        $this->hooklist[] = new $people();
    }

    // 触发事件
    public function exec() {
        foreach ($this->hooklist as $people) {
            $addon->act();
        }
    }
}

// 钩子实现

class man {
    public function act() {
        echo 'notiong';
    }
}

class WoMan {
    public function act() {
        echo 'oh my god ';
    }
}

class child {
    public function act() {
        echo 'oh my god ';
    }
}

$ball = new Ball();

$ball->down();

$ball->do();

class Hook {
    private $hookList;
    //添加
    function add($name, $fun) {
        $this->hookList[$name][] = $fun;
    }

    function excec($name) {
        $value = func_get_args();
        unset($value[0]);
        foreach ($this->hookList[$name] as $key => $fun) {
            call_user_func_array($fun, $value);
        }
    }
}

$hook = new Hook();
$hook->add('women', function ($msg) {
    echo 'oh my god' . $msg;
});

$hook->add('man', function ($msg) {
    echo 'nothing' . $msg;
});

// 执行
$hook->excec('man', 'taoge');
$hook->excec('women', 'xxx');

?>


返回顶部