PHP Classes

File: examples/usingAttributes.php

Recommend this page to a friend!
  Classes of Mateo   PHP JSON Decoder into an Object   examples/usingAttributes.php   Download  
File: examples/usingAttributes.php
Role: Example script
Content type: text/plain
Description: Example script
Class: PHP JSON Decoder into an Object
Decode JSON into an object of a given class
Author: By
Last change:
Date: 11 months ago
Size: 662 bytes
 

Contents

Class file image Download
<?php

use Mateodioev\Json\JSON;

require
__DIR__.'/../vendor/autoload.php';

class
User {
    public
int $id;
    public
string $name;
    public
string $username;

   
// Using attribute for arrays
    #[Mateodioev\Json\JsonField(Product::class)]
   
public array $product;
}

class
Product {
    public
int $id;
    public
string $name;
    public
float $price;
}

$rawJson = '{
    "id": 1,
    "name": "John Doe",
    "username": "johndoe",
    "product": [
        {
            "id": 1,
            "name": "Product 1",
            "price": 10.99
        },
        {
            "id": 2,
            "name": "Product 2",
            "price": 20.99
        }
    ]
}'
;

$u = new User;
JSON::new($rawJson)->decode($u);
var_dump($u);