首页 > 解决方案 > php 类到 Json 预计只返回设置值

问题描述

我有一个具有多个属性的类,所有这些属性都是可选的,但可以接受空或 null 作为值。将类转换为 JSON 对象时,我要求它仅返回正在设置的类的那些属性。

我无法过滤最终结果,因为该值可以为 null 或空,这是一个有效的条目。所以简而言之,我只想要那些调用了 setter 函数的属性。

<?php    
class MyClass{

public $property1;
public $property2;
public $property3;
public $property4;
public $property5;

public function setProperty1($property1){
    $this->property1 = $property1;
    return $this;
}

public function setProperty2($property2){
    $this->property2 = $property2;
    return $this;
}

public function setProperty3($property3){
    $this->property3 = $property3;
    return $this;
}

public function setProperty4($property4){
    $this->property4 = $property4;
    return $this;
}

public function setProperty5($property5){
    $this->property5 = $property5;
    return $this;
}
}

$obj = new MyClass();
$obj->setProperty1("p1");
$obj->setProperty2("");
$obj->setProperty3(null);
echo json_encode($obj);

输出:{"property1":"p1","property2":"","property3":null,"property4":null,"property5":null}

预期的: {"property1":"p1","property2":"","property3":null}

标签: phpoop

解决方案


推荐阅读