PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

BinaryTides.com: Javascript style object literals in PHP

Note: This article was originally published at PHPDeveloper on 26 July 2012.
PHPDeveloper

On the BinaryTides.com site there's a recent post for those familiar with Javascript and wanting to have the same kind of object-style literals in PHP.

As similar thing [to Javascript object literals] can be done in PHP using anonymous functions (since 5.3) [...] Since version 5.3 Php added support for closures and that feature has been used above to create javascript style object literals. The use(&$a) expression makes the variable $a available inside the function happy.

Code snippets are included showing how to create these objects via the use of closures and a little trickery with call_user_func_array and __call to make assigning properties easier.