函数使用变量引用

时间:2014-11-17 02:41:10

标签: php variables reference global

$ret = array();

$params = array(
                    "conTableArry"=>array("connection"=> parent::PDO_("geo", false),"table"=>"locations"),
                    "fields"=>array("ID", "LOCALITY_ID", "COUNTY", "LAT_", "LONG_", "ZIPCODE"),
                    "condArry"=>$condArry,
                    "LIMIT"=>2
                );
                parent::search($params, function($location) use (&$ret){
                    echo "a";
                    $params = array(
                        "conTableArry"=>array("connection"=> parent::PDO_("geo", false),"table"=>"locality"),
                        "fields"=>array("ID","NAME","PROVINCE_ID"),
                        "condArry"=>array(array("ID",$location["LOCALITY_ID"])),
                        "LIMIT"=>2
                    );
                    $_usable_ = array($location, $ret);
                    parent::search($params, function($locality) use (&$_usable_){
                        $params = array(
                            "conTableArry"=>array("connection"=> parent::PDO_("geo", false),"table"=>"provinces"),
                            "fields"=>array("ID","NAME","ABBR"),
                            "condArry"=>array(array("ID",$locality["PROVINCE_ID"])),
                            "LIMIT"=>2
                        );
                        $_usable_ = array($_usable_[0], $locality, $_usable_[1]);
                        parent::search($params, function($province) use(&$_usable_){
                            **$val = array($_usable_[0], $_usable_[1], $province);
                            echo "<br>-";
                            print_r($val);
                            echo "<br>-";
                            print_r($_usable_[0]);
                            echo "<br>-";
                            print_r($_usable_[0]);
                            echo "<br>-";
                            print_r($province);
                            echo "<br>-";
                            array_push($_usable_[2], $val);**
                        });
                    });
                });
return $ret;

将我的$ val推入$ _usable后[2](应该是原来的ret) 我的$ ret仍然返回一个空数组。 我100%确定$ val不为null,并包含另一个数组(我测试过)。

问题是我相信通过参考。

我想避免在函数内部使用return,所以通过引用传递是这里的方法。

1 个答案:

答案 0 :(得分:0)

显然有一个bug, 在数组中传递引用变量时,数组会克隆该值。

PHP数组不是像C ++那样的引用。

class obj_{
    $ret = 0;
    $set = 1;
    protected alpha() use (&$ret, &$set){
         function alpha_brava() use (&$ret, &$set){
             $ret += $set; 
        }
    }
}

回报应为1。