PHP syntax for dereferencing function result

后端 未结 22 858
不知归路
不知归路 2020-11-22 02:14

Background

In every other programming language I use on a regular basis, it is simple to operate on the return value of a function without declaring

相关标签:
22条回答
  • 2020-11-22 02:44

    You can't chain expressions like that in PHP, so you'll have to save the result of array_test() in a variable.

    Try this:

    function array_test() {
      return array(0, 1, 2);
    }
    
    $array = array_test();
    echo $array[0];
    
    0 讨论(0)
  • 2020-11-22 02:45

    Write a wrapper function that will accomplish the same. Because of PHP's easy type-casting this can be pretty open-ended:

    function array_value ($array, $key) {
    return $array[$key];
    }
    
    0 讨论(0)
  • 2020-11-22 02:46

    This is specifically array dereferencing, which is currently unsupported in php5.3 but should be possible in the next release, 5.4. Object dereferencing is on the other hand possible in current php releases. I'm also looking forward to this functionality!

    0 讨论(0)
  • 2020-11-22 02:48

    Actually, I've written a library which allows such behavior:

    http://code.google.com/p/php-preparser/

    Works with everything: functions, methods. Caches, so being as fast as PHP itself :)

    0 讨论(0)
  • 2020-11-22 02:49

    Array Dereferencing is possible as of PHP 5.4:

    • http://svn.php.net/viewvc?view=revision&revision=300266

    Example (source):

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

    with PHP 5.3 you'd get

    Parse error: syntax error, unexpected '[', expecting ',' or ';' 
    

    Original Answer:

    This has been been asked already before. The answer is no. It is not possible.

    To quote Andi Gutmans on this topic:

    This is a well known feature request but won't be supported in PHP 5.0. I can't tell you if it'll ever be supported. It requires some research and a lot of thought.

    You can also find this request a number of times in the PHP Bugtracker. For technical details, I suggest you check the official RFC and/or ask on PHP Internals.

    0 讨论(0)
  • 2020-11-22 02:51

    Short Answer:

    Yes. It is possible to operate on the return value of a function in PHP, so long as the function result and your particular version of PHP support it.

    Referencing example2:

    //  can php say "homer"?      
    //  print zoobar()->fname;     //  homer <-- yup
    

    Cases:

    • The function result is an array and your PHP version is recent enough
    • The function result is an object and the object member you want is reachable
    0 讨论(0)
提交回复
热议问题