PHP syntax for dereferencing function result

后端 未结 22 1222
不知归路
不知归路 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";
    

提交回复
热议问题