缺少某些属性的对象的Php json

缺少某些属性的对象的Php json,php,json,class,Php,Json,Class,我有一个php类,当我json\u encode文件时,我没有得到json字符串中的Total,Subtotal,我如何才能做到这一点 class sale{ public $Customer; public $DiscountRate; public $TaxRate; public $SaleItems; public function Total() { // .... } public function Subtotal() { // .... } } 您可以将JsonSerial

我有一个php类,当我
json\u encode
文件时,我没有得到json字符串中的Total,Subtotal,我如何才能做到这一点

class sale{

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

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

您可以将
JsonSerializable
接口应用于类,并实现
jsonSerialize()
方法。此方法的返回值将用作
json\u encode()
函数的输入

class Sale implements JsonSerializable {

    public $customer;

    public function total() {
        return 40;
    }

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

json编码编码的是实例的属性,而不是方法。。。。你真的希望json_encode自动将PHP代码(及其所有潜在的依赖项、数据库访问等)转换为javascript代码吗?不,但我需要编码的总计和小计的值,那么我如何实现这一点,正如John在回答中所建议的,并将这两个调用的结果作为附加属性添加。请举个例子,你能帮忙吗?