News Archive
PhpRiot Newsletter
Your Email Address:

More information

Features in PHP trunk: Array dereferencing

Note: This article was originally published at Planet PHP on 31 July 2010.
Planet PHP

I was writing about new features in the upcoming PHP version (5.4, 6.0?) before. Today's topic reads like this in the NEWS file:

- Added array dereferencing support. (Felipe)

Now you might wonder what this typical short entry means. when doing OO-style PHP you might make use of a sntax feature which one might call "object dereferencing" which looks like this:

func()-bar(); ?

So one can chain method calls or property access. Now for a long time people requested the same thing for array offset access. This was often rejected due to uncertainties about memory issues, as we don't like memory leaks. But after proper evaluation Felipe committed the patch which allows you to do things like

foo()[2]; // prints 3 ?

Of course this also works with closures:

$func()[0]; // prints a ?

And even though the following example is stupid I might accept this feature might make one of the few places where it is ok to use references in PHP:

&get_data() { return $GLOBALS['data']; } get_data()[2] = 'I'; // $data will now contain 'me', 'myself' and 'I' ?

Wonderful, isn't it? If you want to test it please take a look at the recent snapshots for PHP trunk and send us your feedback! Please mind that all features in PHP trunk may or may not appear in the next major PHP release.