Home > php教程 > PHP源码 > 一个基于PHP的事件机制

一个基于PHP的事件机制

PHP中文网
Release: 2016-05-25 17:14:40
Original
1262 people have browsed it

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.

?>
Copy after login
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template