note 130035 added to language.oop5.property-hooks
| From: | malferov@gmail.com | Date: | Mon, 17 Feb 2025 16:16:07 +0000 |
| Subject: | note 130035 added to language.oop5.property-hooks | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-221859@lists.php.net to get a copy of this message | ||
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 initialized and only public properties instead of
false; the restriction isâthe object must remain empty and not set the uninitialized properties
to null:
<?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}
?>
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.137 (proxied: 95.25.91.102)
----
Manual Page -- https://php.net/manual/en/language.oop5.property-hooks.php
Edit -- https://main.php.net/note/edit/130035
Del: integrated -- https://main.php.net/note/delete/130035/integrated
Del: useless -- https://main.php.net/note/delete/130035/useless
Del: bad code -- https://main.php.net/note/delete/130035/bad+code
Del: spam -- https://main.php.net/note/delete/130035/spam
Del: non-english -- https://main.php.net/note/delete/130035/non-english
Del: in docs -- https://main.php.net/note/delete/130035/in+docs
Del: other reasons-- https://main.php.net/note/delete/130035
Reject -- https://main.php.net/note/reject/130035
Search -- https://main.php.net/manage/user-notes.php