欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  php教程

一个基于PHP的事件机制

程序员文章站 2022-05-14 10:01:38
...
php代码
<?php
//EventUtils:

final class EventArgs { 
}

interface EventHandler { 
public function Invoke($Sender, EventArgs $E); 
}

class Event { 
private $EventHandlerList = array ();

public function AddEventHandler(EventHandler $EventHandler) { 
   $this->EventHandlerList[] = $EventHandler; 
}

public function DeleteEventHandler(EventHandler $EventHandler) { 
   $Index = array_search($EventHandler, $this->EventHanlerList); 
   array_splice($this->EventHanlerList, $Index, 1); 
} 

public function Invoke($Sender, EventArgs $E) { 
   foreach ($this->EventHandlerList as $EventHandler) { 
    $EventHandler->Invoke($Sender, $E); 
   } 
}

}

//Test Case:

class TestEventHandler implements EventHandler { 
public function Invoke($Sender, EventArgs $E) { 
   // echo "Hello, ".$Sender; 
} 
}

TestEvent();

function TestEvent() { 
   $Event = new Event(); 
   $EventHandler = new TestEventHandler(); 
   $Event->AddEventHandler($EventHandler); 
   $Event->Invoke($Event, new EventArgs()); 
}

//Output:

//Hello, Object id #5ok.

?>