PHP execute

Jun 23, 2016 pm 02:37 PM

修改一下文章,之前没说明问题。

主要说明一下PHP的执行过程,涉及到函数执行流程,PHP 的函数让PHP强大的特点之一,暂时不讨论类。PHP 的作用域控制只有两处,函数和类,在实际中感觉函数控制作用域的概念更多一点。

函数分为用户自定义函数,和内部函数。内部函数是php用C 或者是C++编写,这里分析的时候,不会涉及到作用域的切换,在模块初始化的时候就会加载到全局的函数表中EG(function_table)。

内部函数,用户自定义函数,op_array 三者的数据结构如下所示:

struct _zend_op_array {	/* Common elements */	zend_uchar type;	char *function_name;			zend_class_entry *scope;	zend_uint fn_flags;	union _zend_function *prototype;	zend_uint num_args;	zend_uint required_num_args;	zend_arg_info *arg_info;	zend_bool pass_rest_by_reference;	unsigned char return_reference;	/* END of common elements */	zend_bool done_pass_two;	zend_uint *refcount;	zend_op *opcodes;	zend_uint last, size;	zend_compiled_variable *vars;	int last_var, size_var;	zend_uint T;	zend_brk_cont_element *brk_cont_array;	int last_brk_cont;	int current_brk_cont;	zend_try_catch_element *try_catch_array;	int last_try_catch;	/* static variables support */	HashTable *static_variables;	zend_op *start_op;	int backpatch_count;	zend_uint this_var;	char *filename;	zend_uint line_start;	zend_uint line_end;	char *doc_comment;	zend_uint doc_comment_len;	zend_uint early_binding; /* the linked list of delayed declarations */	void *reserved[ZEND_MAX_RESERVED_RESOURCES];};typedef struct _zend_internal_function {	/* Common elements */	zend_uchar type;	char * function_name;	zend_class_entry *scope;	zend_uint fn_flags;	union _zend_function *prototype;	zend_uint num_args;	zend_uint required_num_args;	zend_arg_info *arg_info;	zend_bool pass_rest_by_reference;	unsigned char return_reference;	/* END of common elements */	void (*handler)(INTERNAL_FUNCTION_PARAMETERS);	struct _zend_module_entry *module;} zend_internal_function;typedef union _zend_function {	zend_uchar type;	/* MUST be the first element of this struct! */	struct {		zend_uchar type;  /* never used */		char *function_name;		zend_class_entry *scope;		zend_uint fn_flags;		union _zend_function *prototype;		zend_uint num_args;		zend_uint required_num_args;		zend_arg_info *arg_info;		zend_bool pass_rest_by_reference;		unsigned char return_reference;	} common;	zend_op_array op_array;	zend_internal_function internal_function;} zend_function;typedef struct _zend_function_state {	zend_function *function;	void **arguments;} zend_function_state
로그인 후 복사

这三个数据结构之间可以相互转换,我在上面也列出了一个_zend_function_state 的数据结构,会讲op_array 中的 function 赋值给执行数据_zend_execute_data 的function_state字段的 function,从而将普通代码中切入一个函数,对于作用域的切换稍后说明。

在excute 执行过程中,有EX(function_state).function = (zend_function *) op_array;可以说明一切。

一个重要的数据结构:

struct _zend_execute_data {	struct _zend_op *opline;	zend_function_state function_state;	zend_function *fbc; /* Function Being Called */	zend_class_entry *called_scope;	zend_op_array *op_array;	zval *object;	union _temp_variable *Ts;	zval ***CVs;	HashTable *symbol_table;	struct _zend_execute_data *prev_execute_data;	zval *old_error_reporting;	zend_bool nested;	zval **original_return_value;	zend_class_entry *current_scope;	zend_class_entry *current_called_scope;	zval *current_this;	zval *current_object;	struct _zend_op *call_opline;}
로그인 후 복사

用于保存执行期间的数据,在作用域切换的时候起至关重要的作用。

ZEND_API void execute(zend_op_array *op_array TSRMLS_DC){	zend_execute_data *execute_data;	zend_bool nested = 0;	zend_bool original_in_execution = EG(in_execution);	if (EG(exception)) {		return;	}	EG(in_execution) = 1;zend_vm_enter:	/* Initialize execute_data */	execute_data = (zend_execute_data *)zend_vm_stack_alloc(		ZEND_MM_ALIGNED_SIZE(sizeof(zend_execute_data)) +		ZEND_MM_ALIGNED_SIZE(sizeof(zval**) * op_array->last_var * (EG(active_symbol_table) ? 1 : 2)) +		ZEND_MM_ALIGNED_SIZE(sizeof(temp_variable)) * op_array->T TSRMLS_CC);	EX(CVs) = (zval***)((char*)execute_data + ZEND_MM_ALIGNED_SIZE(sizeof(zend_execute_data)));	memset(EX(CVs), 0, sizeof(zval**) * op_array->last_var);	EX(Ts) = (temp_variable *)(((char*)EX(CVs)) + ZEND_MM_ALIGNED_SIZE(sizeof(zval**) * op_array->last_var * (EG(active_symbol_table) ? 1 : 2)));	EX(fbc) = NULL;	EX(called_scope) = NULL;	EX(object) = NULL;	EX(old_error_reporting) = NULL;	EX(op_array) = op_array;	EX(symbol_table) = EG(active_symbol_table);	EX(prev_execute_data) = EG(current_execute_data);	EG(current_execute_data) = execute_data;	EX(nested) = nested;	nested = 1;	if (op_array->start_op) {		ZEND_VM_SET_OPCODE(op_array->start_op);	} else {		ZEND_VM_SET_OPCODE(op_array->opcodes);	}	if (op_array->this_var != -1 && EG(This)) { 		Z_ADDREF_P(EG(This)); /* For $this pointer */		if (!EG(active_symbol_table)) {			EX(CVs)[op_array->this_var] = (zval**)EX(CVs) + (op_array->last_var + op_array->this_var);			*EX(CVs)[op_array->this_var] = EG(This);		} else {			if (zend_hash_add(EG(active_symbol_table), "this", sizeof("this"), &EG(This), sizeof(zval *), (void**)&EX(CVs)[op_array->this_var])==FAILURE) {				Z_DELREF_P(EG(This));			}		}	}	EG(opline_ptr) = &EX(opline);	EX(function_state).function = (zend_function *) op_array;	EX(function_state).arguments = NULL;		while (1) {    	int ret;#ifdef ZEND_WIN32		if (EG(timed_out)) {			zend_timeout(0);		}#endif		if ((ret = EX(opline)->handler(execute_data TSRMLS_CC)) > 0) {			switch (ret) {				case 1:					EG(in_execution) = original_in_execution;					return;				case 2:					op_array = EG(active_op_array);					goto zend_vm_enter;				case 3:					execute_data = EG(current_execute_data);				default:					break;			}		}	}	zend_error_noreturn(E_ERROR, "Arrived at end of main loop which shouldn't happen");}
로그인 후 복사

执行期间 有EX(prev_execute_data) = EG(current_execute_data);会保存一下现场,

然后EG(current_execute_data) = execute_data;

当执行到函数的op_array时,EG(active_op_array) = &EX(function_state).function->op_array;

会执行到

   case 2:
     op_array = EG(active_op_array);
     goto zend_vm_enter;

当函数将要执行完毕或者返回的时候,可以主动调用return 或者PHP 会自动放回一个NULL,然后是zend_do_return 生成 ZEND_RETURN的opcode ,根据类型不同会调用几个不同的函数,但总之会调用一个名为zend_leave_helper_SPEC 的函数,其中:

EG(current_execute_data) = EX(prev_execute_data);会将返回以前的场景,保证回到执行函数以前的作用域。

个人觉得关键的是以上的一些数据结构,以及相互之间的联系。

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 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 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 아무도들을 수없는 경우 오디오를 수정하는 방법
3 몇 주 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

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

SublimeText3 중국어 버전

SublimeText3 중국어 버전

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

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

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

Laravel의 플래시 세션 데이터로 작업합니다 Laravel의 플래시 세션 데이터로 작업합니다 Mar 12, 2025 pm 05:08 PM

Laravel은 직관적 인 플래시 방법을 사용하여 임시 세션 데이터 처리를 단순화합니다. 응용 프로그램에 간단한 메시지, 경고 또는 알림을 표시하는 데 적합합니다. 데이터는 기본적으로 후속 요청에만 지속됩니다. $ 요청-

PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 PHP의 컬 : REST API에서 PHP Curl Extension 사용 방법 Mar 14, 2025 am 11:42 AM

PHP 클라이언트 URL (CURL) 확장자는 개발자를위한 강력한 도구이며 원격 서버 및 REST API와의 원활한 상호 작용을 가능하게합니다. PHP CURL은 존경받는 다중 프로모토콜 파일 전송 라이브러리 인 Libcurl을 활용하여 효율적인 execu를 용이하게합니다.

PHP 로깅 : PHP 로그 분석을위한 모범 사례 PHP 로깅 : PHP 로그 분석을위한 모범 사례 Mar 10, 2025 pm 02:32 PM

PHP 로깅은 웹 애플리케이션을 모니터링하고 디버깅하고 중요한 이벤트, 오류 및 런타임 동작을 캡처하는 데 필수적입니다. 시스템 성능에 대한 귀중한 통찰력을 제공하고 문제를 식별하며 더 빠른 문제 해결을 지원합니다.

Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Laravel 테스트에서 단순화 된 HTTP 응답 조롱 Mar 12, 2025 pm 05:09 PM

Laravel은 간결한 HTTP 응답 시뮬레이션 구문을 제공하여 HTTP 상호 작용 테스트를 단순화합니다. 이 접근법은 테스트 시뮬레이션을보다 직관적으로 만들면서 코드 중복성을 크게 줄입니다. 기본 구현은 다양한 응답 유형 단축키를 제공합니다. Illuminate \ support \ Facades \ http를 사용하십시오. http :: 가짜 ([ 'google.com'=> ​​'Hello World', 'github.com'=> ​​[ 'foo'=> 'bar'], 'forge.laravel.com'=>

Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Codecanyon에서 12 개의 최고의 PHP 채팅 스크립트 Mar 13, 2025 pm 12:08 PM

고객의 가장 긴급한 문제에 실시간 인스턴트 솔루션을 제공하고 싶습니까? 라이브 채팅을 통해 고객과 실시간 대화를 나누고 문제를 즉시 해결할 수 있습니다. 그것은 당신이 당신의 관습에 더 빠른 서비스를 제공 할 수 있도록합니다.

PHP에서 늦은 정적 결합의 개념을 설명하십시오. PHP에서 늦은 정적 결합의 개념을 설명하십시오. Mar 21, 2025 pm 01:33 PM

기사는 PHP 5.3에 도입 된 PHP의 LSB (Late STATIC BING)에 대해 논의하여 정적 방법의 런타임 해상도가보다 유연한 상속을 요구할 수있게한다. LSB의 실제 응용 프로그램 및 잠재적 성능

프레임 워크 사용자 정의/확장 : 사용자 정의 기능을 추가하는 방법. 프레임 워크 사용자 정의/확장 : 사용자 정의 기능을 추가하는 방법. Mar 28, 2025 pm 05:12 PM

이 기사에서는 프레임 워크에 사용자 정의 기능 추가, 아키텍처 이해, 확장 지점 식별 및 통합 및 디버깅을위한 모범 사례에 중점을 둡니다.

See all articles