- 观察者模式
<?php class dingdaguo { protected $observers = []; public function addobserver($myobserver) { $this->observers[] = $myobserver; } public function drink_cola() { foreach($this->observers as $observer) { $observer->persuade(); } } public function delobsrver($observer) { $index = array_search($observer,$this->observers,); $this->observers=array_slice($this->observers,0,$index); } } class coach { public function __construct($name) { $this->name = $name; } public function persuade() { echo $this->name."说:别喝可乐了,都是甜的东西".PHP_EOL; } } $cpc = new coach("陈培昌"); $cj = new coach("程劲"); $dy = new dingdaguo(); $dy->addobserver($cpc); $dy->addobserver($cj); $dy->drink_cola();
echo "删除其中一个对象".PHP_EOL;
$dy->delobsrver($cj);
$dy->drink_cola();
输出结果:
陈培昌说:别喝可乐了,都是甜的东西
程劲说:别喝可乐了,都是甜的东西
删除其中一个对象
陈培昌说:别喝可乐了,都是甜的东西