The json_encode() function returns false when trying to serialize an object that contains a property with only a set hook, but without a get hook, because the function seeks to get the property value from the get hook and returns false if no such hook has been defined.
The following example shows how, when serializing an object with the json_encode() function, to get an empty serialized object, or object with only public initialized properties instead of false; the restriction is—the object must remain empty and not set the uninitialized properties to null, if they are not initialized with other values:
<?php
class Lambic
implements JsonSerializable
{
public int $age {
set => $value;
}
#[Override]
public function jsonSerialize(): stdClass
{
return (object) get_mangled_object_vars($this);
}
public function __construct(?int $age = null)
{
if ($age !== null) {
$this->age = $age;
}
}
}
$noagedLambic = new Lambic();
var_dump(json_encode($noagedLambic)); $agedLambic = new Lambic(20);
var_dump(json_encode($agedLambic)); ?>