kaasplootz/object-parser

Parse objects to JSON and back, with just two functions.

1.2.1 2022-03-02 20:04 UTC

This package is auto-updated.

Last update: 2025-05-29 01:55:55 UTC


README

GitHub stars GitHub issues GitHub license Packagist Version

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