PHP 5.5+ library to create object literals like JavaScript or Ruby.
Creating object literals in PHP is not as easy (or elegant) as in JavaScript or Ruby.
You can create object literals this way:
$object = new Object([
"name" => "Fido",
"barks" => true,
"age" => 10
]);
or
$object = new Object([
"name" => "Fido",
"barks" => true,
"age" => 10,
'say' => function ($self) {
if ($self->barks) {
return "Woof";
}
return "";
}
]);
or
$object = new Object('{
"name" : "Fido",
"barks" : true,
"age" : 10
}');
instead of:
$object = new Object();
$object->name = 'Fido';
$object->barks = true;
$object->age = 10;
This class was inspired by these two blog posts:
- https://www.sitepoint.com/php-vs-ruby-lets-all-just-get-along/
- https://www.phpied.com/javascript-style-object-literals-in-php/
In fact, there is am old PHP RFC (2011-06-04) which have not been completely implemented:
This class could be used while the RFC is not implemented.
Via Composer
$ composer require josecelano/php-object-literal
- Build from array.
- Build from json.
- Build from json with dynamic keys and values.
I try to follow TDD, as such I use phpunit to test this library.
$ composer test
- Add magic getters and setters.
- Allow to replace variable values in Json like JavaScript: From:
$object = new Object("{
\"name\" : \"" . $valueForName . "\",
\"barks\" : true,
\"age\" : 10
}");
To:
$object = new Object('{
"name" : $valueForName,
"barks" : true,
"age" : 10
}', get_defined_vars());
Replacing $valueForName
by its value.
- Allow current invalid PHP json formats.
$invalidJson1 = "{ 'bar': 'baz' }";
$invalidJson2 = '{ bar: "baz" }';
$invalidJson3 = '{ bar: "baz", }';
- Add callable in json format.
- Allow property value shorthand like ES6:
$object = new Object('{
$name,
$barks,
$age
}', get_defined_vars());
The MIT License (MIT). Please see License File for more information.