Heim > Artikel > Backend-Entwicklung > Detaillierte Erklärung der Echo-Anweisung in PHP
Dieser Artikel vermittelt Ihnen ein tiefgreifendes Verständnis der Echo-Anweisung in PHP. Es hat einen gewissen Referenzwert. Freunde in Not können sich darauf beziehen. Ich hoffe, es wird für alle hilfreich sein.
echo
wird oft als Sprachstruktur in PHP verwendet, daher ist es notwendig, seine Implementierung zu verstehen.echo
作为PHP中的语言结构, 经常会被使用, 因此了解他的实现还是有必要的.
版本 | 源码地址 | ||||||||||||||||||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PHP-7.2.8
2、官方文档(php.net)2.1 输出一个或多个字符串void echo ( string $arg1 [, string $... ] )
2.2 说明
2.3 注释
<?php /** * Tip * 相对 echo 中拼接字符串而言,传递多个参数比较好,考虑到了 PHP 中连接运算符(“.”)的优先级。 传入多个参数,不需要圆括号保证优先级: */ echo "Sum: ", 1 + 2; echo "Hello ", isset($name) ? $name : "John Doe", "!"; /** Tip * 如果是拼接的,相对于加号和三目元算符,连接运算符(“.”)具有更高优先级。为了正确性,必须使用圆括号: */ echo 'Sum: ' . (1 + 2); echo 'Hello ' . (isset($name) ? $name : 'John Doe') . '!'; 3、应用3.1 输出基本数据类型echo 123, 'abc', [12, 34]; // 123abcArray echo "Sum: ", 1 + 2; // Sum: 3 echo 'Sum: ' . (1 + 2); // Sum: 3 echo "Hello ", isset($name) ? $name : "John Doe", "!"; // Hello John Doe! echo 'Hello ' . (isset($name) ? $name : 'John Doe') . '!'; // Hello John Doe! 3.2 输出对象类型<?php class Customer { public function say() { return 'Hello World'; } } echo (new Customer());
输出对象时汇报以上错误, 所以如果需要输出对象, 一定要在其内部实现 <?php class Customer { public function say() { return 'Hello World'; } /** * __toString() 方法用于一个类被当成字符串时应怎样回应。例如 echo $obj; 应该显示些什么。此方法必须返回一个字符串,否则将发出一条 E_RECOVERABLE_ERROR 级别的致命错误。 */ public function __toString(){ return $this->say(); } } echo (new Customer()); // Hello World 3.3 输出资源类型echo tmpfile(); // Resource id #1 4、源码4.1 源码概述
对应的文件在 4.2 字符转标记(Zend/zend_language_scanner.l)<ST_IN_SCRIPTING>"echo" { RETURN_TOKEN(T_ECHO); } ZEND引擎在读取一个PHP文件之后会先进行词法分析,就是用lex扫描,把对应的PHP字符转换成相应的标记(也叫token),比如 4.3 语法分析(Zend/zend_language_parser.y)# %token Token就是一个个的“词块” %token T_ECHO "echo (T_ECHO)" # statement T_ECHO echo_expr_list statement: '{' inner_statement_list '}' { ? = $2; } | if_stmt { ? = $1; } | alt_if_stmt { ? = $1; } | T_WHILE '(' expr ')' while_statement { ? = zend_ast_create(ZEND_AST_WHILE, $3, $5); } | T_DO statement T_WHILE '(' expr ')' ';' { ? = zend_ast_create(ZEND_AST_DO_WHILE, $2, $5); } | T_FOR '(' for_exprs ';' for_exprs ';' for_exprs ')' for_statement { ? = zend_ast_create(ZEND_AST_FOR, $3, $5, $7, $9); } | T_SWITCH '(' expr ')' switch_case_list { ? = zend_ast_create(ZEND_AST_SWITCH, $3, $5); } | T_BREAK optional_expr ';' { ? = zend_ast_create(ZEND_AST_BREAK, $2); } | T_CONTINUE optional_expr ';' { ? = zend_ast_create(ZEND_AST_CONTINUE, $2); } | T_RETURN optional_expr ';' { ? = zend_ast_create(ZEND_AST_RETURN, $2); } | T_GLOBAL global_var_list ';' { ? = $2; } | T_STATIC static_var_list ';' { ? = $2; } | T_ECHO echo_expr_list ';' { ? = $2; } | T_INLINE_HTML { ? = zend_ast_create(ZEND_AST_ECHO, $1); } | expr ';' { ? = $1; } | T_UNSET '(' unset_variables ')' ';' { ? = $3; } | T_FOREACH '(' expr T_AS foreach_variable ')' foreach_statement { ? = zend_ast_create(ZEND_AST_FOREACH, $3, $5, NULL, $7); } | T_FOREACH '(' expr T_AS foreach_variable T_DOUBLE_ARROW foreach_variable ')' foreach_statement { ? = zend_ast_create(ZEND_AST_FOREACH, $3, $7, $5, $9); } | T_DECLARE '(' const_list ')' { zend_handle_encoding_declaration($3); } declare_statement { ? = zend_ast_create(ZEND_AST_DECLARE, $3, $6); } | ';' /* empty statement */ { ? = NULL; } | T_TRY '{' inner_statement_list '}' catch_list finally_statement { ? = zend_ast_create(ZEND_AST_TRY, $3, $5, $6); } | T_THROW expr ';' { ? = zend_ast_create(ZEND_AST_THROW, $2); } | T_GOTO T_STRING ';' { ? = zend_ast_create(ZEND_AST_GOTO, $2); } | T_STRING ':' { ? = zend_ast_create(ZEND_AST_LABEL, $1); } ; 在 # echo_expr_list echo_expr_list: echo_expr_list ',' echo_expr { ? = zend_ast_list_add($1, $3); } | echo_expr { ? = zend_ast_create_list(1, ZEND_AST_STMT_LIST, $1); } ; echo_expr: expr { ? = zend_ast_create(ZEND_AST_ECHO, $1); } ; expr: variable { ? = $1; } | expr_without_variable { ? = $1; } ; 词法分析后得到单独存在的词块不能表达完整的语义,还需要借助规则进行组织串联。语法分析器就是这个组织者。它会检查语法、匹配Token,对Token进行关联。PHP7中,组织串联的产物就是抽象语法树( 这么看比较难理解,接下来我们从一个简单的例子看下最终生成的语法树。 $a = 123; $b = "hi~"; echo $a,$b; 具体解析过程这里不再解释,有兴趣的可以翻下zend_language_parse.y中,这个过程不太容易理解,需要多领悟几遍,最后生成的ast如下图: 4.4 模块初始化(main/main.c)通过 # php_module_startup zend_utility_functions zuf; // ... gc_globals_ctor(); zuf.error_function = php_error_cb; zuf.printf_function = php_printf; zuf.write_function = php_output_wrapper; zuf.fopen_function = php_fopen_wrapper_for_zend; zuf.message_handler = php_message_handler_for_zend; zuf.get_configuration_directive = php_get_configuration_directive_for_zend; zuf.ticks_function = php_run_ticks; zuf.on_timeout = php_on_timeout; zuf.stream_open_function = php_stream_open_for_zend; zuf.printf_to_smart_string_function = php_printf_to_smart_string; zuf.printf_to_smart_str_function = php_printf_to_smart_str; zuf.getenv_function = sapi_getenv; zuf.resolve_path_function = php_resolve_path_for_zend; zend_startup(&zuf, NULL);
/* {{{ php_output_wrapper */ static size_t php_output_wrapper(const char *str, size_t str_length) { return php_output_write(str, str_length); } 在 /* {{{ int php_output_write(const char *str, size_t len) * Buffered write * #define PHP_OUTPUT_ACTIVATED 0x100000 * 当flags=PHP_OUTPUT_ACTIVATED,会调用sapi_module.ub_write输出, 每个SAPI都有自已的实现, cli中是调用sapi_cli_single_write() * php_output_write(); //输出,有buffer, 调用php_output_op() * php_output_write_unbuffered();//输出,没有buffer,调用PHP_OUTPUT_ACTIVATED,会调用sapi_module.ub_write * php_output_set_status(); //用于SAPI设置output.flags * php_output_get_status(); //获取output.flags的值 */ PHPAPI size_t php_output_write(const char *str, size_t len) { if (OG(flags) & PHP_OUTPUT_ACTIVATED) { php_output_op(PHP_OUTPUT_HANDLER_WRITE, str, len); return len; } if (OG(flags) & PHP_OUTPUT_DISABLED) { return 0; } return php_output_direct(str, len); } /* }}} */ 4.5 输出的终点(main/output.c fwrite函数)不调用sapi_module的输出 static size_t (*php_output_direct)(const char *str, size_t str_len) = php_output_stderr; static size_t php_output_stderr(const char *str, size_t str_len) { fwrite(str, 1, str_len, stderr); /* See http://support.microsoft.com/kb/190351 */ #ifdef PHP_WIN32 fflush(stderr); #endif return str_len; } 调用sapi_module的输出 sapi_module.ub_write(context.out.data, context.out.used); if (OG(flags) & PHP_OUTPUT_IMPLICITFLUSH) { sapi_flush(); }
/* {{{ static void php_output_op(int op, const char *str, size_t len) * Output op dispatcher, passes input and output handlers output through the output handler stack until it gets written to the SAPI */ static inline void php_output_op(int op, const char *str, size_t len) { php_output_context context; php_output_handler **active; int obh_cnt; if (php_output_lock_error(op)) { return; } php_output_context_init(&context, op); /* * broken up for better performance: * - apply op to the one active handler; note that OG(active) might be popped off the stack on a flush * - or apply op to the handler stack */ if (OG(active) && (obh_cnt = zend_stack_count(&OG(handlers)))) { context.in.data = (char *) str; context.in.used = len; if (obh_cnt > 1) { zend_stack_apply_with_argument(&OG(handlers), ZEND_STACK_APPLY_TOPDOWN, php_output_stack_apply_op, &context); } else if ((active = zend_stack_top(&OG(handlers))) && (!((*active)->flags & PHP_OUTPUT_HANDLER_DISABLED))) { php_output_handler_op(*active, &context); } else { php_output_context_pass(&context); } } else { context.out.data = (char *) str; context.out.used = len; } if (context.out.data && context.out.used) { php_output_header(); if (!(OG(flags) & PHP_OUTPUT_DISABLED)) { #if PHP_OUTPUT_DEBUG fprintf(stderr, "::: sapi_write('%s', %zu)\n", context.out.data, context.out.used); #endif sapi_module.ub_write(context.out.data, context.out.used); if (OG(flags) & PHP_OUTPUT_IMPLICITFLUSH) { sapi_flush(); } OG(flags) |= PHP_OUTPUT_SENT; } } php_output_context_dtor(&context); } 以上了解了PHP输出函数的实现, 接下来了解echo实现. 4.6 输出动作的ZEND引擎实现(Zend/zend_vm_def.h)ZEND_VM_HANDLER(40, ZEND_ECHO, CONST|TMPVAR|CV, ANY) { USE_OPLINE zend_free_op free_op1; zval *z; SAVE_OPLINE(); z = GET_OP1_ZVAL_PTR_UNDEF(BP_VAR_R); if (Z_TYPE_P(z) == IS_STRING) { zend_string *str = Z_STR_P(z); if (ZSTR_LEN(str) != 0) { zend_write(ZSTR_VAL(str), ZSTR_LEN(str)); } } else { zend_string *str = _zval_get_string_func(z); if (ZSTR_LEN(str) != 0) { zend_write(ZSTR_VAL(str), ZSTR_LEN(str)); } else if (OP1_TYPE == IS_CV && UNEXPECTED(Z_TYPE_P(z) == IS_UNDEF)) { GET_OP1_UNDEF_CV(z, BP_VAR_R); } zend_string_release(str); } FREE_OP1(); ZEND_VM_NEXT_OPCODE_CHECK_EXCEPTION(); } 可以看到在 4.7 zend_write实现(Zend/zend.c)# Zend/zend.h typedef int (*zend_write_func_t)(const char *str, size_t str_length); # Zend/zend.c ZEND_API zend_write_func_t zend_write; # 如下图所示, zend_write的初始化是在zend_startup()函数里面,这是zend引擎启动的时候需要做的一些初始化工作,有下面一句: zend_write = (zend_write_func_t) utility_functions->write_function; // php_output_wrapper
zuf.write_function = php_output_wrapper; 5、php(echo)加速5.1 PHP echo 真的慢么?
但是在某些时候 那么使用 5.2 还是可以优化的: 打开输出缓存
# 编辑php.ini output_buffering = 4096 //bytes # 调用ob_start() ob_start(); echo $hugeString; ob_end_flush();
6、输出时的类型转换6.1 输出时的类型转换规则
6.2 输出时的类型转换源码(Zend/zend_operators.h & Zend/zend_operators.c)# Zend/zend_operators.h ZEND_API zend_string* ZEND_FASTCALL _zval_get_string_func(zval *op); # Zend/zend_operators.c ZEND_API zend_string* ZEND_FASTCALL _zval_get_string_func(zval *op) /* {{{ */ { try_again: switch (Z_TYPE_P(op)) { case IS_UNDEF: case IS_NULL: case IS_FALSE: return ZSTR_EMPTY_ALLOC(); case IS_TRUE: if (CG(one_char_string)['1']) { return CG(one_char_string)['1']; } else { return zend_string_init("1", 1, 0); } case IS_RESOURCE: { char buf[sizeof("Resource id #") + MAX_LENGTH_OF_LONG]; int len; len = snprintf(buf, sizeof(buf), "Resource id #" ZEND_LONG_FMT, (zend_long)Z_RES_HANDLE_P(op)); return zend_string_init(buf, len, 0); } case IS_LONG: { return zend_long_to_str(Z_LVAL_P(op)); } case IS_DOUBLE: { return zend_strpprintf(0, "%.*G", (int) EG(precision), Z_DVAL_P(op)); } case IS_ARRAY: zend_error(E_NOTICE, "Array to string conversion"); return zend_string_init("Array", sizeof("Array")-1, 0); case IS_OBJECT: { zval tmp; if (Z_OBJ_HT_P(op)->cast_object) { if (Z_OBJ_HT_P(op)->cast_object(op, &tmp, IS_STRING) == SUCCESS) { return Z_STR(tmp); } } else if (Z_OBJ_HT_P(op)->get) { zval *z = Z_OBJ_HT_P(op)->get(op, &tmp); if (Z_TYPE_P(z) != IS_OBJECT) { zend_string *str = zval_get_string(z); zval_ptr_dtor(z); return str; } zval_ptr_dtor(z); } zend_error(EG(exception) ? E_ERROR : E_RECOVERABLE_ERROR, "Object of class %s could not be converted to string", ZSTR_VAL(Z_OBJCE_P(op)->name)); return ZSTR_EMPTY_ALLOC(); } case IS_REFERENCE: op = Z_REFVAL_P(op); goto try_again; case IS_STRING: return zend_string_copy(Z_STR_P(op)); EMPTY_SWITCH_DEFAULT_CASE() } return NULL; } /* }}} */ 7、Zend/zend_compile.c对echo的解析7.1 源码地址7.2 |
Das obige ist der detaillierte Inhalt vonDetaillierte Erklärung der Echo-Anweisung in PHP. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!