I have a class with multiple properties, all of which are optional, but can accept empty or null as a value. When converting the class to a JSON object, I require it to return only those properties of the class which are being set.
I can't filter then the final result since the value can be null or empty which is a valid entry. So in short, I want only those properties for whose setter functions had been called.
<?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);
Output:{"property1":"p1","property2":"","property3":null,"property4":null,"property5":null}
Expected:
{"property1":"p1","property2":"","property3":null}