tags:

views:

24

answers:

2

I'm searching for a short syntax like in PERL

<?php
    # instead of this ( PHP )
    $f = returnArray(); 
    echo $f[2];
    unset($f);

    # just do this ( PERL short code )
    echo (returnArray())[2];

    # or this ( PERL short code )
    echo returnArray()->[2];

    function returnArray()
    {
        return array(0=>'x', 1=>'y', 2=>'This will get printed');
    }
?>

The first echo will print This will get printed
The second and third are syntax errors

There is a way of doing something like this in PHP ?

Thank you

A: 

No, PHP doesn't support this yet. (According to Gordon it is already in the trunk.)

But you may write a small function:

function arrayOffset($array, $index) {
    return $array[$index];
}

arrayOffset(func(), 2);

PS: Actually I have an implementation of this feature in prephp, but I don't think it shall be used. It may be buggy and I haven't developed the project for quite some time (though I hope to resume). (Test, Implementation)

nikic
You might want to add a "yet" to that, because it's actually in the trunk, but not yet available in any of the releases
Gordon
Edited my answer. Nice to here that it is on the way. Will this feature be available in 5.4 or will it already land in 5.3.4 (or some other 5.3 version)?
nikic
I dont know when it will be available. Please see the link below the question for details.
Gordon
A: 

PHP does not support this in it's current version. For the next upcoming release of php there plans to include this feature.

See the php.net wiki (this rfc and related ones) or the blog post of the php 5.3 release manager.

For now one thing that works is:

<?php
function x() { return array(1,2,3); }
list($one, $two, ) = x();

and so on. Maybe other people will post more examples but a general workarround looking as nice.. i don't know of.

edorian