有時候咱們會遇到對php提供的函數執行結果感到詫異,這時候咱們須要看下源碼的實現,才能作出更好的解釋。php
首先在php.net官網下載php源碼。mysql
下載好的源碼,咱們須要重點關注的是ext和zend兩個目錄。其餘目錄能夠不用關心。sql
ext目錄下放的是php裏面的擴展。包括咱們常用的一些核心函數(json_encode、json_decode),同時也包括mysqli、PDO等核心類。json
zend目錄下放的是zend引擎的源碼。控制PHP代碼運行時候的運行環境。它處理PHP提供的全部「語言層」的特性,包括:變量,表達式,語法解析,代碼執行和錯誤處理。函數
假設咱們想知道json_encode怎麼實現,只需在整個目錄中搜索 _function(json_encode)。就能夠發現json_encode的源碼是在json.c文件中的。spa
同理找strlen方法。.net
仔細看就會發現,兩個搜索結果略有差別。 一個是PHP_FUNCTION,一個是ZEND_FUNCTION。一個是zend引擎定義的函數,一個是PHP擴展的函數。code
在json.c文件中,能夠很輕鬆找出json_encode的實現代碼以下。ip
/* {{{ proto string json_encode(mixed data [, int options[, int depth]]) Returns the JSON representation of a value */ static PHP_FUNCTION(json_encode) { zval *parameter; smart_str buf = {0}; zend_long options = 0; zend_long depth = PHP_JSON_PARSER_DEFAULT_DEPTH; if (zend_parse_parameters(ZEND_NUM_ARGS(), "z|ll", ¶meter, &options, &depth) == FAILURE) { return; } JSON_G(error_code) = PHP_JSON_ERROR_NONE; JSON_G(encode_max_depth) = (int)depth; php_json_encode(&buf, parameter, (int)options); if (JSON_G(error_code) != PHP_JSON_ERROR_NONE && !(options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR)) { smart_str_free(&buf); ZVAL_FALSE(return_value); } else { smart_str_0(&buf); /* copy? */ ZVAL_NEW_STR(return_value, buf.s); } } /* }}} */
剩下的就是要讀懂這段代碼,後面再講……o(╯□╰)oget