PHP 8.5.0 Beta 1 available for testing

Voting

: four minus three?
(Example: nine)

The Note You're Voting On

malferov at gmail dot com
5 months ago
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
// Implementing an interface to intercept json_encode() serialization
implements JsonSerializable
{
// Note: The property with the set hook only
/** @var int It must be typed if need to omit an uninitialized property in output object */
public int $age {
set => $value;
}

/**
* Implements the interface method
*/
#[Override]
public function
jsonSerialize(): stdClass
{
// Cast the array to an object to get an empty serialized object when object does not contain initialized properties
return (object) get_mangled_object_vars($this);
}

public function
__construct(?int $age = null)
{
if (
$age !== null) {
$this->age = $age;
}
}
}

// Get the empty serialized object without properties
$noagedLambic = new Lambic();
var_dump(json_encode($noagedLambic)); // {} and not {"age":null}

// ...and with properties if initialized
$agedLambic = new Lambic(20);
var_dump(json_encode($agedLambic)); // {"age":20}

?>

<< Back to user notes page

To Top