json_encode()
如何轉化一個對象? 使用json_encode()
將數組array
轉化成json
字符串咱們都已經很熟悉了php那麼使用
json_encode()
轉化一個對象是什麼樣的過程呢?json
咱們須要新建一個具備多種屬性的對象數組
JsonTest
class JsonTest {
public const TEST = 'c';
public $a = 'a';
public static $b = 'b';
protected $e = 'e';
private $d = 'd';
protected function test1() {
return __FUNCTION__;
}
private function test2() {
return __FUNCTION__;
}
public function test3() {
return __FUNCTION__;
}
public static function test4() {
return __FUNCTION__;
}
}
複製代碼
打印結果bash
echo json_encode(new JsonTest());
複製代碼
輸出app
{ "a": "a" }
複製代碼
能夠看得出,只有公開非靜態的屬性被打印出來了,其餘東西(常量、私有變量、方法等等)都丟失了。函數
在實際的應用中,多數狀況下,咱們的屬性都是非公開的,可是咱們又想在執行 json_encode()
的時候將它打印出來,該怎麼辦呢?源碼分析
JsonSerializable
JsonSerializable 是一個 PHP 的 JSON 序列化接口post
JSON 序列化接口
(PHP 5 >= 5.4.0, PHP 7)測試
簡介
實現 JsonSerializable 的類能夠 在 json_encode() 時定製他們的 JSON 表示法。this
接口摘要
JsonSerializable {
/* 方法 */
abstract public jsonSerialize ( void ) : mixed
}
複製代碼
能夠看出 php
版本低於 5.4
是沒有這個接口的
JsonTest
繼續測試修改
JsonTest
讓它實現JsonSerializable
,併爲其寫一個jsonSerialize
方法
class JsonTest implements JsonSerializable {
public const TEST = 'c';
public $a = 'a';
public static $b = 'b';
protected $e = 'e';
private $d = 'd';
protected function test1() {
return __FUNCTION__;
}
private function test2() {
return __FUNCTION__;
}
public function test3() {
return __FUNCTION__;
}
public static function test4() {
return __FUNCTION__;
}
public function jsonSerialize() {
$json = array();
foreach ($this as $key => $value) {
$json[$key] = $value;
}
return $json;
}
}
複製代碼
打印結果
echo json_encode(new JsonTest());
複製代碼
輸出
{ "a": "a", "e": "e", "d": "d" }
複製代碼
能夠看得出,公開屬性和私有屬性都被打印出來了,方法,常量以及靜態變量沒有打印出來(這是由於類(class
)中靜態變量和常量的實現方式是全部對象共享的,並不具體屬於某個類)
這部分源碼較多,我會按照源碼中的
function
來一個一個進行分析,注意看代碼塊中的註釋裏邊對應有一些
option
的位運算,我先貼出來每一個option
常量對應的值,<<
是左移
/* json_encode() options */
#define PHP_JSON_HEX_TAG (1<<0)
#define PHP_JSON_HEX_AMP (1<<1)
#define PHP_JSON_HEX_APOS (1<<2)
#define PHP_JSON_HEX_QUOT (1<<3)
#define PHP_JSON_FORCE_OBJECT (1<<4)
#define PHP_JSON_NUMERIC_CHECK (1<<5)
#define PHP_JSON_UNESCAPED_SLASHES (1<<6)
#define PHP_JSON_PRETTY_PRINT (1<<7)
#define PHP_JSON_UNESCAPED_UNICODE (1<<8)
#define PHP_JSON_PARTIAL_OUTPUT_ON_ERROR (1<<9)
#define PHP_JSON_PRESERVE_ZERO_FRACTION (1<<10)
#define PHP_JSON_UNESCAPED_LINE_TERMINATORS (1<<11)
複製代碼
PHP_JSON_API int php_json_encode(smart_str *buf, zval *val, int options) /* {{{ */ {
return php_json_encode_ex(buf, val, options, JSON_G(encode_max_depth));
}
PHP_JSON_API int php_json_encode_ex(smart_str *buf, zval *val, int options, zend_long depth) /* {{{ */ {
php_json_encoder encoder;
int return_code;
// 初始化,開闢內存空間
php_json_encode_init(&encoder);
encoder.max_depth = depth;
// 真正用於編碼的函數體
return_code = php_json_encode_zval(buf, val, options, &encoder);
JSON_G(error_code) = encoder.error_code;
return return_code;
}
/* }}} */
複製代碼
能夠看出真正的編碼函數是 php_json_encode_zval()
php_json_encode_zval()
smart_str_appendl()
是一個拼接字符串的函數,第三個參數是字符串的長度
buf
就是最終要返回的json
字符串
int php_json_encode_zval(smart_str *buf, zval *val, int options, php_json_encoder *encoder) /* {{{ */ {
again:
switch (Z_TYPE_P(val))
{
case IS_NULL:
smart_str_appendl(buf, "null", 4);
break;
case IS_TRUE:
smart_str_appendl(buf, "true", 4);
break;
case IS_FALSE:
smart_str_appendl(buf, "false", 5);
break;
case IS_LONG:
smart_str_append_long(buf, Z_LVAL_P(val));
break;
case IS_DOUBLE:
if (php_json_is_valid_double(Z_DVAL_P(val))) {
php_json_encode_double(buf, Z_DVAL_P(val), options);
} else {
encoder->error_code = PHP_JSON_ERROR_INF_OR_NAN;
smart_str_appendc(buf, '0');
}
break;
case IS_STRING:
return php_json_escape_string(buf, Z_STRVAL_P(val), Z_STRLEN_P(val), options, encoder);
case IS_OBJECT:
// 若是對象實現了JsonSerializable,就將對象中的jsonSerialize()返回的結果進行編碼
if (instanceof_function(Z_OBJCE_P(val), php_json_serializable_ce)) {
return php_json_encode_serializable_object(buf, val, options, encoder);
}
// 若是對象沒有實現了JsonSerializable,就執行下邊的這個php_json_encode_array()
/* fallthrough -- Non-serializable object */
case IS_ARRAY:
// 解析數組
return php_json_encode_array(buf, val, options, encoder);
case IS_REFERENCE:
//忽略引用
val = Z_REFVAL_P(val);
goto again;
default:
encoder->error_code = PHP_JSON_ERROR_UNSUPPORTED_TYPE;
if (options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR) {
smart_str_appendl(buf, "null", 4);
}
return FAILURE;
}
return SUCCESS;
}
/* }}} */
複製代碼
php_json_encode_array()
這個函數遞歸編碼數組及沒有實現
JsonSerializable()
的對象(只編碼對象的公開屬性)
static int php_json_encode_array(smart_str *buf, zval *val, int options, php_json_encoder *encoder) /* {{{ */ {
int i, r, need_comma = 0;
HashTable *myht;
// r用來表示輸出 `json` 的結構類型是數組仍是對象
// 只有天然排序的數組(['a','b','c'])纔有可能被輸出爲數組(考慮option可能爲JSON_FORCE_OBJECT)
if (Z_TYPE_P(val) == IS_ARRAY) {
// 若是是數組
myht = Z_ARRVAL_P(val);
// options中有JSON_FORCE_OBJECT 就強制輸出對象,不然就判斷數組是否是天然數組
r = (options & PHP_JSON_FORCE_OBJECT) ? PHP_JSON_OUTPUT_OBJECT : php_json_determine_array_type(val);
} else {
myht = Z_OBJPROP_P(val);
//對象就是輸出對象
r = PHP_JSON_OUTPUT_OBJECT;
}
if (myht && ZEND_HASH_GET_APPLY_COUNT(myht) > 0) {
encoder->error_code = PHP_JSON_ERROR_RECURSION;
smart_str_appendl(buf, "null", 4);
return FAILURE;
}
PHP_JSON_HASH_APPLY_PROTECTION_INC(myht);
if (r == PHP_JSON_OUTPUT_ARRAY) {
//輸出爲數組 就用 [ 作開頭
smart_str_appendc(buf, '[');
} else {
//輸出爲對象 就用 { 作開頭
smart_str_appendc(buf, '{');
}
// 當前遞歸的深度
++encoder->depth;
// zend_hash_num_elements 返回哈希表中元素的數量
i = myht ? zend_hash_num_elements(myht) : 0;
if (i > 0) {
zend_string *key;
zval *data;
zend_ulong index;
//遍歷當前維度的數組 若是當前元素不是數組
ZEND_HASH_FOREACH_KEY_VAL_IND(myht, index, key, data) {
// ↓ begin 從這裏開始都是判斷key怎麼處理以及元素末尾怎麼處理 ↓↓↓↓
if (r == PHP_JSON_OUTPUT_ARRAY) {
//need_comma初始值是0
if (need_comma) {
smart_str_appendc(buf, ',');
} else {
need_comma = 1;
}
//這兩個方法是option中有JSON_PRETTY_PRINT的時候纔會執行的
php_json_pretty_print_char(buf, options, '\n');
php_json_pretty_print_indent(buf, options, encoder);
} else if (r == PHP_JSON_OUTPUT_OBJECT) {
if (key) {
if (ZSTR_VAL(key)[0] == '\0' && ZSTR_LEN(key) > 0 && Z_TYPE_P(val) == IS_OBJECT) {
//跳過受保護的屬性和私有屬性
/* Skip protected and private members. */
continue;
}
//need_comma初始值是0
if (need_comma) {
smart_str_appendc(buf, ',');
} else {
need_comma = 1;
}
php_json_pretty_print_char(buf, options, '\n');
php_json_pretty_print_indent(buf, options, encoder);
// 處理字符串屬性的key(例如判斷key中的中文或者特殊字符的處理)
if (php_json_escape_string(buf, ZSTR_VAL(key), ZSTR_LEN(key),
options & ~PHP_JSON_NUMERIC_CHECK, encoder) == FAILURE &&
(options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR) &&
buf->s) {
ZSTR_LEN(buf->s) -= 4;
smart_str_appendl(buf, "\"\"", 2);
}
} else {
if (need_comma) {
smart_str_appendc(buf, ',');
} else {
need_comma = 1;
}
php_json_pretty_print_char(buf, options, '\n');
php_json_pretty_print_indent(buf, options, encoder);
smart_str_appendc(buf, '"');
smart_str_append_long(buf, (zend_long) index);
smart_str_appendc(buf, '"');
}
smart_str_appendc(buf, ':');
php_json_pretty_print_char(buf, options, ' ');
}
// ↑ end 從這裏以前都是判斷key怎麼處理以及元素末尾怎麼處理 ↑↑↑↑
//繼續調用對普通元素編碼的 php_json_encode_zval() (實現數組和對象的遞歸閉環)
if (php_json_encode_zval(buf, data, options, encoder) == FAILURE &&
!(options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR)) {
PHP_JSON_HASH_APPLY_PROTECTION_DEC(myht);
return FAILURE;
}
} ZEND_HASH_FOREACH_END();
}
PHP_JSON_HASH_APPLY_PROTECTION_DEC(myht);
// 當前深度是否到達了設定的最大深度(默認512)
if (encoder->depth > encoder->max_depth) {
encoder->error_code = PHP_JSON_ERROR_DEPTH;
if (!(options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR)) {
return FAILURE;
}
}
--encoder->depth;
/* Only keep closing bracket on same line for empty arrays/objects */
if (need_comma) {
php_json_pretty_print_char(buf, options, '\n');
php_json_pretty_print_indent(buf, options, encoder);
}
if (r == PHP_JSON_OUTPUT_ARRAY) {
smart_str_appendc(buf, ']');
} else {
smart_str_appendc(buf, '}');
}
return SUCCESS;
}
/* }}} */
複製代碼
看了源碼,我得出了一些結論。
JsonSerializable
並定義一個 jsonSerialize()
,要麼就被當成一個數組,只會被處理公開非靜態屬性json_encode()
並不會直接編碼數組和對象,而是會遞歸遍歷出全部可遍歷的元素,並處理 keyphp_json_encode_zval()
和 php_json_encode_array()
的相互調用,實現了數組和對象遍歷的閉環另外,關於 json_encode()
的 options
,我以爲這裏處理的技巧很是有趣,巧妙利用位運算來區別多個常量,有興趣的慢慢看看研究研究。(提示,將 options
每一個常量轉成二進制來看,json_encode()
接受多個 option
是按位或 |
)
>>> $a = [1,2,3,4];
=> [
1,
2,
3,
4,
]
>>> json_encode($a);
=> "[1,2,3,4]"
>>> json_encode((object)$a);
=> "{"0":1,"1":2,"2":3,"3":4}"
>>> json_encode($a,JSON_FORCE_OBJECT);
=> "{"0":1,"1":2,"2":3,"3":4}"
>>> json_encode($a,JSON_FORCE_OBJECT|JSON_PRETTY_PRINT);
=> """ {\n "0": 1,\n "1": 2,\n "2": 3,\n "3": 4\n } """
複製代碼