2015-07-04 18 views
3

我很困惑JsonSerializable如何工作。讓我再詳細說一下這個問題。PHP如何使用JsonSerializable接口?

通常我們使用的接口是這樣的:

<?php 
interface Countable { 
    /* Methods */ 
    public function count();  
} 

class MyThings implements Countable 
{ 
    public function count() { 
     return count($this->arrayOfThings); 
    } 
} 


$obj = new MyThings(); 

//call count method on $obj 
$obj->count(); 

因此,我們有一個類,它實現了接口。當我們調用count()函數時,它已經寫入MyThings類。這很容易理解。

但是,當我們使用JsonSerializable接口這樣的:

<?php 
class Thing implements JsonSerializable { 
    public function jsonSerialize() { 
     // do something 
    } 
} 
$obj = new Thing(); 

//call count method on $obj 
json_encode($obj); 

jsonSerialize()Thing運行與json_encode()通話。 如果我們調用

$obj->jsonSerialize(); 

然後有一個叫jsonSerialize()裏面的類功能,是可以理解的。但是,當我們運行json_encode()時,這是如何工作的?這是如何構建在PHP?有人可以解釋這裏使用的模式類型嗎?

回答

1

implementJsonSerializable然後執行jsonSerialize()方法的對象。然後,當json_encode()將其輸入序列化爲JSON時,如果它正在序列化的值是JsonSerializable,則它調用jsonSerialize()方法,並且該方法的結果被用作對象的序列化表示。

例如,來自PHP文檔:

<?php 
class IntegerValue implements JsonSerializable { 
    public function __construct($number) { 
     $this->number = (integer) $number; 
    } 

    public function jsonSerialize() { 
     return $this->number; 
    } 
} 

echo json_encode(new IntegerValue(1), JSON_PRETTY_PRINT); 

將輸出

1 

其是代表數字1。json_encode d值的PHP文檔提供了三個例子像這樣,從對象返回值,但由於jsonSerialize()允許您指定要返回的實際數據,因此它是導入的螞蟻意識到它可以返回任何東西。例如:

class JsonSerializeExample implements JsonSerializable { 
    public function jsonSerialize() { 
     return [ 
      'boolean' => true, 
      'random_integer' => rand(), 
      'int_from_object' => new IntegerValue(42), 
      'another_object' => new stdClass, 
     ]; 
    } 
} 
$obj = new JsonSerializeExample(); 
echo json_encode($obj, JSON_PRETTY_PRINT); 

將輸出

{ 
    "boolean": true, 
    "random_integer": 1140562437, 
    "int_from_object": 42, 
    "another_object": {} 
} 

值得注意的是,random_integer不存儲靜態值;它在每次執行時都會改變;和int_from_object表明json_encode()將遞歸評估JsonSerializable實例。