PHP syntax for dereferencing function result

后端 未结 22 1154
不知归路
不知归路 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: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);
    }
    

提交回复
热议问题