kaasplootz / object-parser
Parse objects to JSON and back, with just two functions.
1.2.1
2022-03-02 20:04 UTC
README
Example
PHP8 object to JSON:
<?php namespace example; use kaasplootz\objectParser\ObjectParser; class SameName extends ObjectParser {} class Friend extends ObjectParser {} class User extends ObjectParser { public function __construct( public int $id, public string $username, private string $private, public float $float, public SameName $sameName, public SameName $otherName, public array $friends, public ?string $nullable = null ) {} public function getPrivate(): string { return $this->private; } } $user = new User( 1, 'username', 'privateValue', 1.0, new SameName(), new SameName(), [ new Friend() ] ); echo $user->toJSON();
JSON result:
{ "id": 1, "username": "username", "private": "privateValue", "float": 1, "SameName": {}, "otherName": { "SameName": {} }, "friends": [ { "Friend": {} } ], "nullable": null }
don't be surprised: JSON can't store x.0 as float
JSON to object:
<?php /* @var User $user */ $user = User::fromJSON(' { "id": 1, ... } '); echo $userObject->getPrivate(); // privateValue