I am trying to json_encode
an array of objects who all have magic properties using __get
and __set
. json_encode
completely ignores these, resulting in an array of empty objects (all the normal properties are private
or protected
).
So, imagine this class:
class Foo
{
public function __get($sProperty)
{
if ($sProperty == 'foo')
{
return 'bar!';
}
return null;
}
}
$object = new Foo();
echo $object->foo; // echoes "foo"
echo $object->bar; // warning
echo json_encode($object); // "{}"
I've tried implementing IteratorAggregate
and Serializable
for the class, but json_encode
still doesn't see my magic properties. Since I am trying to encode an array of these objects, an AsJSON()
-method on the class won't work either.
Update! It seems the question is easy to misunderstand. How can I tell json_encode
which "magic properties" exist? IteratorAggregate
didn't work.
BTW: The term from the PHP documentation is "dynamic entities". Whether or not the magic properties actually exist is arguing about semantics.
I think json_encode makes sure that php can read the . json file but you have to specify a variable name, whereas with json_decode it's the same but you have to specify a file name.
The json_encode() function is used to encode a value to JSON format.
Syntax. The json_encode() function can return a string containing the JSON representation of supplied value. The encoding is affected by supplied options, and additionally, the encoding of float values depends on the value of serialize_precision.
json_encode(mixed $value , int $flags = 0, int $depth = 512): string|false. Returns a string containing the JSON representation of the supplied value . If the parameter is an array or object, it will be serialized recursively.
PHP 5.4 has an interface called JsonSerializable
. It has one method, jsonSerialize
which will return the data to be encoded. This problem would be easily fixed by implementing it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With