php教程 php手册 PHP 事件机制(2)

PHP 事件机制(2)

Jun 21, 2016 am 08:55 AM
class event function method

复制代码 代码如下:


class Event extends stdClass{
public $target=null;
public $type=null;
/**
* 创建事件
* @param string $type
*/
public function __construct($type){
$this->type=trim($type);
}
/**
* 得到事件字符串
*/
public function __toString(){
return $this->type;
}
}

abstract class EventDispatcher{
private $_callback_method;
/**
* 添加事件
* @param Event $event
* @param string $method
* @param stringobject $class
* @return boolean true
*/
public function attach($event,$method,$class=null){
$eventstr=(string)$event;
if($this->has($event,$method,$class))
return true;
if($class!=null){
$this->_check_method($class,$method);
$this->_callback_method[$eventstr][]=$this->_create_listener_method($eventstr,$class,$method);
}else{
$this->_check_function($method);
$this->_callback_method[$eventstr][]=$this->_create_listener_fn($eventstr,$method);
}
return true;
}
/**
* 派发事件
* @param Event $event
* @param string $method
* @param stringobject $class
* @return void
*/
public function dispatch(Event $event){
$event->target=$this;
$eventstr=(string)$event;
if($this->_check_callback($eventstr)){
foreach ($this->_callback_method[$eventstr] as $v){
if($v['object']){
if(is_object($v['class'])){
$v['class']->$v['method']($event);
}else{
call_user_func(array($v['class'], $v['method']),$event);
}
}else{
$v['function']($event);
}
}
}
}
/**
* 删除事件
* @param Event $event
* @param string $method
* @param string $class
* @return boolean true
*/
public function detact($event,$method,$class=null){
$eventstr=(string)$event;
if(!$this->_check_callback($eventstr))
return true;
if(!$this->has($event,$method,$class))
return true;
if($class!=null){
$this->_check_method($class,$method);
foreach ($this->_callback_method[$eventstr] as $k=>$v) {
if(($v==$this->_create_listener_method($eventstr,$class,$method))){
unset($this->_callback_method[$eventstr][$k]);
return true;
}
}
return true;
}else{
$this->_check_function($method);
foreach ($this->_callback_method[$eventstr] as $k=>$v) {
if(($v==$this->_create_listener_fn($eventstr,$method))){
unset($this->_callback_method[$eventstr][$k]);
return true;
}
}
return true;
}
}
/**
* 检测事件是否监听
* @param Event $event
* @param string $method
* @param string $class
* @return boolean
*/
public function has($event,$method,$class=null){
$eventstr=(string)$event;
if(($class!=null)){
$this->_check_method($class,$method);
if($this->_check_callback($eventstr)){
foreach($this->_callback_method[$eventstr] as $v){
if(is_object($v['class'])){
$v_class=get_class($v['class']);
}else{
$v_class=$v['class'];
}
if(is_object($class)){
$s_class=get_class($class);
}else{
$s_class=$class;
}
$temp_v=array(
"class"=>$v_class,
"method"=>$method,
);
$temp_s=array(
"class"=>$s_class,
"method"=>$method,
);
if($temp_v==$temp_s){
return true;
}
}
}
}else{
$this->_check_function($method);
if($this->_check_callback($eventstr)){
foreach($this->_callback_method[$eventstr] as $v){
if($method==$v['function']){
return true;
}
}
}
}
return false;
}
/**
* 检测指定类是否存在指定方法
* @param string $class
* @param string $method
* @exception Exception_Event
* @return void
*/
private function _check_method($class,$method){
if(!method_exists($class,$method)){
throw new Exception(get_class($class)." not exist ".$method." method",1);
}
}
/**
* 检测指定函数是否存在
* @param string $function
* @return void
*/
private function _check_function($function){
if(!function_exists($function)){
throw new Exception($function." function not exist ",2);
}
}
/**
* 检测指定事件是否存在监听函数
* @param string $eventstr
* @return boolean
*/
private function _check_callback($eventstr){
if(isset($this->_callback_method[$eventstr])
&&is_array($this->_callback_method[$eventstr])
){
return true;
}
return false;
}
/**
* 创建监听函数数组
* @param string $eventstr
* @param string $function
* @return array
*/
private function _create_listener_fn($eventstr,$function){
return array(
"object"=>false,
"function"=>$function,
);
}
/**
* 创建监听类数组
* @param string $eventstr
* @param string $class
* @param string $method
* @return array
*/
private function _create_listener_method($eventstr,$class,$method){
return array(
"object"=>true,
"class"=>$class,
"method"=>$method,
);
}
}



class myevent extends Event{
const aa='aaa';
}
class ball extends EventDispatcher{
public function aa(){
$event=new myevent(myevent::aa);
$this->dispatch($event);
}
}

class mytest {
public function test(){
$ball=new ball();
$ball->attach(myevent::aa,'kk');
$ball->aa();
}
public function kk($e){
print_r($e);
}
}


try{
$t=new mytest();
$t->test();
}catch (Exception $e){
echo $e->getmessage();
}



본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

Python에서 클래스와 메서드를 사용하는 방법 Python에서 클래스와 메서드를 사용하는 방법 Apr 21, 2023 pm 02:28 PM

클래스와 메소드의 개념과 인스턴스 클래스(Class): 동일한 속성과 메소드를 가진 객체의 컬렉션을 설명하는 데 사용됩니다. 컬렉션의 모든 개체에 공통적인 속성과 메서드를 정의합니다. 객체는 클래스의 인스턴스입니다. 메소드: 클래스에 정의된 함수입니다. 클래스 구성 메서드 __init__(): 클래스에는 클래스가 인스턴스화될 때 자동으로 호출되는 init()라는 특수 메서드(구성 메서드)가 있습니다. 인스턴스 변수: 클래스 선언에서 속성은 변수로 표시됩니다. 이러한 변수를 인스턴스 변수라고 합니다. 인스턴스화: 클래스의 특정 개체인 클래스의 인스턴스를 만듭니다. 상속: 즉, 파생 클래스(derivedclass)가 기본 클래스(baseclass)를 상속합니다.

기능은 무슨 뜻인가요? 기능은 무슨 뜻인가요? Aug 04, 2023 am 10:33 AM

함수는 특정 기능을 포함하는 재사용 가능한 코드 블록으로, 입력 매개변수를 받아들이고 특정 작업을 수행하며 결과를 반환하는 것이 목적입니다. 코드 재사용성과 유지 관리성을 향상시키는 코드입니다.

PHP 치명적인 오류에 대한 해결 방법: 멤버 함수 fetch() 호출 PHP 치명적인 오류에 대한 해결 방법: 멤버 함수 fetch() 호출 Jun 23, 2023 am 09:36 AM

웹 애플리케이션 개발을 위해 PHP를 사용할 때 데이터베이스를 사용해야 하는 경우가 많습니다. 데이터베이스를 사용할 때 오류 메시지는 매우 일반적입니다. 그 중 PHPFatalerror: Calltoamemberfunctionfetch()는 PDO를 사용하여 데이터베이스를 쿼리할 때 발생하는 비교적 일반적인 오류입니다. 그렇다면 이 오류가 발생하는 원인과 해결 방법은 무엇입니까? 이 기사에서는 이에 대해 자세히 설명합니다. 1. 오류의 원인

jQuery를 사용하여 요소의 클래스 이름 바꾸기 jQuery를 사용하여 요소의 클래스 이름 바꾸기 Feb 24, 2024 pm 11:03 PM

jQuery는 웹 개발에 널리 사용되는 클래식 JavaScript 라이브러리로, 이벤트 처리, DOM 요소 조작, 웹 페이지에서 애니메이션 수행과 같은 작업을 단순화합니다. jQuery를 사용할 때 요소의 클래스 이름을 바꿔야 하는 상황이 자주 발생합니다. 이 기사에서는 몇 가지 실용적인 방법과 구체적인 코드 예제를 소개합니다. 1. RemoveClass() 및 addClass() 메소드 사용 jQuery는 삭제를 위한 RemoveClass() 메소드를 제공합니다.

파이썬에서 클래스는 무엇을 의미합니까? 파이썬에서 클래스는 무엇을 의미합니까? May 21, 2019 pm 05:10 PM

클래스는 클래스를 정의하는 데 사용되는 키워드입니다. 클래스 뒤에 공백을 추가하고 클래스 이름을 추가합니다. 규칙: 첫 글자가 여러 개인 경우 카멜 표기법을 사용합니다. [class Dog()]와 같은 이름 지정.

PHP 클래스 사용법에 대한 자세한 설명: 코드를 더 명확하고 읽기 쉽게 만듭니다. PHP 클래스 사용법에 대한 자세한 설명: 코드를 더 명확하고 읽기 쉽게 만듭니다. Mar 10, 2024 pm 12:03 PM

PHP 코드를 작성할 때 클래스를 사용하는 것은 매우 일반적인 관행입니다. 클래스를 사용하면 관련 함수와 데이터를 단일 단위로 캡슐화하여 코드를 더 명확하고, 읽기 쉽고, 유지 관리하기 쉽게 만들 수 있습니다. 이 기사에서는 PHPClass의 사용법을 자세히 소개하고 구체적인 코드 예제를 제공하여 독자가 실제 프로젝트에 클래스를 적용하여 코드를 최적화하는 방법을 더 잘 이해할 수 있도록 돕습니다. 1. 클래스 생성 및 사용 PHP에서는 클래스 키워드를 사용하여 클래스를 정의하고 클래스의 속성과 메서드를 정의할 수 있습니다.

PHP8.0의 이벤트 처리 라이브러리: 이벤트 PHP8.0의 이벤트 처리 라이브러리: 이벤트 May 14, 2023 pm 05:40 PM

PHP8.0의 이벤트 처리 라이브러리: 이벤트 인터넷의 지속적인 발전과 함께 널리 사용되는 백엔드 프로그래밍 언어인 PHP는 다양한 웹 애플리케이션 개발에 널리 사용됩니다. 이 과정에서 이벤트 중심 메커니즘은 매우 중요한 부분이 되었습니다. PHP8.0의 이벤트 처리 라이브러리 Event는 보다 효율적이고 유연한 이벤트 처리 방법을 제공합니다. 이벤트 처리란 무엇입니까? 이벤트 처리는 웹 애플리케이션 개발에 있어 매우 중요한 개념입니다. 이벤트는 모든 종류의 사용자 행일 수 있습니다.

Vue 오류: v-bind를 사용하여 클래스와 스타일을 올바르게 바인딩할 수 없습니다. 어떻게 해결합니까? Vue 오류: v-bind를 사용하여 클래스와 스타일을 올바르게 바인딩할 수 없습니다. 어떻게 해결합니까? Aug 26, 2023 pm 10:58 PM

Vue 오류: v-bind를 사용하여 클래스와 스타일을 올바르게 바인딩할 수 없습니다. 어떻게 해결합니까? Vue 개발에서는 클래스와 스타일을 동적으로 바인딩하기 위해 v-bind 지시문을 사용하는 경우가 많지만, 클래스와 스타일을 바인딩하기 위해 v-bind를 올바르게 사용하지 못하는 등의 문제가 발생할 수도 있습니다. 이번 글에서는 이 문제의 원인을 설명하고 해결 방법을 알려드리겠습니다. 먼저 v-bind 지시어를 이해해 봅시다. v-bind는 V를 바인딩하는 데 사용됩니다.

See all articles