json_decode to custom class

In PHP, you can use the json_decode() function to convert a JSON string into a PHP object or array. If you want to convert the JSON data into an instance of a custom class, you can use the second parameter of the json_decode() function, which specifies the class to use for the resulting object.

Watch a course Learn object oriented PHP

For example, if you have a JSON string like this:

<?php

$json = '{"name":"John Doe","age":30,"email":"[email protected]"}';

And you have a custom class Person defined like this:

<?php

class Person
{
  public $name;
  public $age;
  public $email;
}

You can create a new instance of the Person class and populate its properties using the values from the decoded JSON:

<?php

$json = '{"name":"John Doe","age":30,"email":"[email protected]"}';

class Person
{
  public $name;
  public $age;
  public $email;
}

$person_array = json_decode($json, true);

print_r($person_array);

Now you can use the $person variable as an instance of the Person class, with the properties name, age, and email set to the values from the JSON string.

<?php

$json = '{"name":"John Doe","age":30,"email":"[email protected]"}';

class Person
{
  public $name;
  public $age;
  public $email;
}

$person_array = json_decode($json, true);

$person = new Person();
$person->name = $person_array['name'];
$person->age = $person_array['age'];
$person->email = $person_array['email'];

echo $person->name; // "John Doe"
echo '-';
echo $person->age; // 30
echo '-';
echo $person->email; // "[email protected]"