PHP syntax for dereferencing function result

后端 未结 22 859
不知归路
不知归路 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:52

    These are some ways to approach your problem.

    First you could use to name variables directly if you return array of variables that are not part of the collection but have separate meaning each.

    Other two ways are for returning the result that is a collection of values.

    function test() {
      return array(1, 2);
    }   
    list($a, $b) = test();
    echo "This should be 2: $b\n";
    
    function test2() {
       return new ArrayObject(array('a' => 1, 'b' => 2), ArrayObject::ARRAY_AS_PROPS);
    }
    $tmp2 = test2();
    echo "This should be 2: $tmp2->b\n";
    
    function test3() {
       return (object) array('a' => 1, 'b' => 2);
    }
    $tmp3 = test3();
    echo "This should be 2: $tmp3->b\n";
    
    0 讨论(0)
  • 2020-11-22 02:52

    Does this work?

     return ($foo->getBarArray())[0];
    

    Otherwise, can you post the getBarArray() function? I don't see why that wouldn't work from what you posted so far.

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

    You could use references:

    $ref =& myFunc();
    echo $ref['foo'];
    

    That way, you're not really creating a duplicate of the returned array.

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

    Well, you could use any of the following solutions, depending on the situation:

    function foo() {
        return array("foo","bar","foobar","barfoo","tofu");
    }
    echo(array_shift(foo())); // prints "foo"
    echo(array_pop(foo())); // prints "tofu"
    

    Or you can grab specific values from the returned array using list():

    list($foo, $bar) = foo();
    echo($foo); // prints "foo"
    echo($bar); // print "bar"
    

    Edit: the example code for each() I gave earlier was incorrect. each() returns a key-value pair. So it might be easier to use foreach():

    foreach(foo() as $key=>$val) {
        echo($val);
    }
    
    0 讨论(0)
  • 2020-11-22 02:56

    There isn't a way to do that unfortunately, although it is in most other programming languages.

    If you really wanted to do a one liner, you could make a function called a() and do something like

    $test = a(func(), 1); // second parameter is the key.
    

    But other than that, func()[1] is not supported in PHP.

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

    After further research I believe the answer is no, a temporary variable like that is indeed the canonical way to deal with an array returned from a function.

    Looks like this will change starting in PHP 5.4.

    Also, this answer was originally for this version of the question:

    How to avoid temporary variables in PHP when using an array returned from a function

    0 讨论(0)
提交回复
热议问题