JavaScript’s Object Literal Notation in PHP
I've found that the more I code in JavaScript, the more I enjoy its expressive syntax over other that of other languages. Object literals, for example, are among my most commonly used patterns:
Sometimes I'll even forget which language I'm in and I'll try something like:
Which gives the result: Parse error: syntax error, unexpected T_DOUBLE_ARROW in test.php on line 1
What you can use in PHP, which are quite elegant and expressive, are associative arrays:
But if you were depending on an object for one reason or another, you can use typecasting to make PHP's syntax more like that of JavaScript:
(Note that the (object) typecasting operator is needed at each level in the array.)
This will also help eliminate strict warnings. Because though you can (depending on your php.ini settings) use this syntax...
... it may give you this warning: Strict standards: Creating default object from empty value in test.php on line 1
This PHP pattern to me is easily readable and makes the language more expressive, like our good friend JavaScript.
Hehe yeah I spent about 5 minutes looking at a bunch of lines of php code for my fuzzer and I couldn’t understand why it didn’t work
for($i=0;$i<len;i++) {
}
DOH!
Damn for loops I code too many in javascript it’s affecting my php brain :)
Strict standards are worth sticking to, especially when considering forward compatibility. Here is another (more) concise way of getting your desired effect that uses the ArrayObject class from the standard php library: http://codepad.org/BxvCjXD2. It gives you the same that you have but also a lot more; you can interact with the object as if it were an array (ArrayAccess, Countable), and do other similar operations on it.
Slight update: http://codepad.org/NWdIX9NE, extending arrayobject would be preferable to allow __get and __set instead of duplicating the data as I have.