php訪問函數外的變量

php在函數內無法訪問函數體外聲明的變量

php版本:7.1.8
運行環境:win7 x64

<?php
    $out = 'outvariables';
    function test(){
        echo $out;//Notice: Undefined variable: $out
    }
    #無法訪問到$out變量

當使用global關鍵字的時候,如果test()中改變了out out也會一起改變

<?php
    $out = 'outvariables';
    function test(){
        global $out;
        $out='another';
        echo $out;
    }
    echo $out;// outvariables
    echo "\n";
    test();// another
    echo "\n";
    echo $out;//another

這樣的結果可能不是我們想要的。

解決方案

使用匿名函數和use關鍵字

<?php
 $out = 3;
 $test = function()use($out){//use 按值
        $out++;
        echo $out;//4  
};

$test();//4
echo $out;//3 $out值並未改變
$test2 = function() use(&$out){//按引用傳參
        $out++;
        echo $out;//4
};
$test2();//4
echo $out;//4 $out 改變

這樣使用&符號就可以靈活的使用外部變量,決定是否需要改變其狀態。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章