I have classes that extends an abstract class. I need to create instances of these classes through a string - preferably JSON.
Many of the objects are nested, and many properties are private. I need a way to:
I guess it needs to be recursive.
I'm using namespaces that end up looking like crap if I just cast the object to an array.
I'm thinking of writing a parser, label the classes in my JSON strings and then hardcode a factory function for every class, but that would take a lot of time.
Firstly read the contents of the text file into a string variable using the file_get_contents() function and then use json_decode() function to convert the JSON string to a PHP variable. $filepath = './persons. txt'; $json_string = file_get_contents($filepath); $json = json_decode($json_string, true);
An object that converts between JSON and the equivalent Foundation objects.
The JsonSerializable::jsonSerialize() function is an inbuilt function in PHP which is used to serialize the JSON object to a value that can be serialized natively by using json_encode() function. Syntax: mixed JsonSerializable::jsonSerialize( void ) Parameters: This function does not accept any parameters.
Serializing an object means converting it to a bytestream representation that can be stored in a file. This is useful for persistent data; for example, PHP sessions automatically save and restore objects.
I suggest using the jms serializer: http://jmsyst.com/libs/serializer Easy to use, configuarble and supports all the features you requested.
I suggest you to use php's serialize function
In cases like this it's better to use this function because it exists for this purpose: you can store the serialized string wherever you want and after unserializing it you will get back the original PHP object with all the properties
With JSON, as you said, you'll have no clue of what class the object was (unless you store it manually as a string) and of course there will be all the problems related to the private properties
There are three methods for doing this: JSON, Serialize, and var_export.
With JSON, it will only work with objects of stdClass, but it's easy to read and can be used outside of PHP.
Serialize works with instances of classes other than stdClass, but it can be difficult to read and can only be used by PHP. http://php.net/manual/en/function.serialize.php
var_export outputs the PHP code to create the object (so you'd write it to a PHP file), it's very easy to read but can't be used outside PHP. The objects will need to have the set state method. http://php.net/manual/en/function.var-export.php
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