Json的php类应仅返回设置值

时间:2019-06-21 08:17:13

标签: php oop

我有一个具有多个属性的类,所有这些都是可选的,但是可以接受空或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}

1 个答案:

答案 0 :(得分:1)

由于已经声明了所有属性,因此无论是否调用setter,您都将在响应中获取它们。

删除声明部分,这样,您将仅获得已调用了setter函数的那些属性。

<?php

class MyClass{


    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);

输出:-https://3v4l.org/biEPB