Array dereferencing in PHP trunk post

Posted on 2010-07-31 by jwage


Today I was reading an article about array dereferencing in PHP trunk. It is an awesome new feature added to PHP! Imagine you had some code like this:

class Foo
{
    public function bar()
    {
    }
}

function func()
{
    return new Foo();
}

Previous to this addition in PHP you had to do something like this:

$foo = func();
$foo->bar();

Now it is possible to just call bar() directly without having to set the return of func() to a variable temporarily:

func()->bar();

You can also now access arrays when they are the return of a method:

function foo()
{
    return array(1, 2, 3);
}
echo foo()[2]; // prints 3

This greatly improves the syntax of PHP and I am very happy to see this committed!