2017-11-10 72 views
-1

我有一個PHP類,當我json_encode文件,我沒有得到總計,小計在JSON字符串,我怎麼能做到這一點,PHP的JSON缺少一些性能

class sale{ 

public $Customer; 
public $DiscountRate; 
public $TaxRate; 
public $SaleItems; 

public function Total() 
{ 
// .... 
} 
public function Subtotal() 
{ 
// .... 
} 
} 
+1

JSON enccoding編碼實例的__properties__,而不是__methods __....你真的希望json_encode,自動將轉換PHP代碼(及其所有可能依賴性,數據庫訪問等),以JavaScript代碼? –

+0

不,但我需要總和小計的編碼值,所以我如何實現這個 – Smith

+1

正如約翰在他的回答中所建議的[JsonSerializable](http://php.net/manual/en/class.jsonserializable.php )並將這兩個調用的結果作爲附加屬性添加 –

回答

4

您可以申請JsonSerializable接口到您的班級並實施jsonSerialize()方法。此方法的返回值將用作json_encode()函數的輸入。

class Sale implements JsonSerializable { 

    public $customer; 

    public function total() { 
     return 40; 
    } 

    public function jsonSerialize() { 
     return [ 
      'customer' => $this->customer, 
      'total' => $this->total() 
     ]; 
    } 
} 
+0

請問你能幫助一個例子嗎? – Smith

+0

@史密斯編輯添加一個例子。 –