1. Go to this page and download the library: Download graywings/instantiate library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
$json = '
{
"id": 1,
"name": "John Doe",
"address": {
"street": "123 Main St",
"city": "New York",
"zipCode": "10001"
}
}';
$user = Instantiate::json(User::class, $json);
// $user->getAddress() will be an Address object with the specified properties
$data = [
'id' => '42', // String will be converted to int
'name' => 'John',
'active' => 1 // Integer will be converted to boolean
];
$user = Instantiate::array(User::class, $data);
// $user->getId() will be an int (42)
// $user->isActive() will be a boolean (true)
enum UserStatus: string {
case ACTIVE = 'active';
case INACTIVE = 'inactive';
case PENDING = 'pending';
}
class User {
public function __construct(
private int $id,
private string $name,
private UserStatus $status
) { }
// Getters...
}
// From string value matching the enum's backing value
$data1 = [
'id' => 1,
'name' => 'John',
'status' => 'active' // Will be converted to UserStatus::ACTIVE
];
// From actual enum instance
$data2 = [
'id' => 2,
'name' => 'Jane',
'status' => UserStatus::PENDING // Direct enum instance
];
$user1 = Instantiate::array(User::class, $data1);
$user2 = Instantiate::array(User::class, $data2);
class User {
public function __construct(
private int $id,
private string $name,
private ?string $email = null,
private int $age = 30,
private bool $active = true
) { }
// Getters...
}
$data = [
'id' => 1,
'name' => 'John'
// email, age, and active are not specified
];
$user = Instantiate::array(User::class, $data);
// $user->getEmail() will be null
// $user->getAge() will be 30
// $user->isActive() will be true