Giving my function access to outside variable

前端 未结 6 1729
梦毁少年i
梦毁少年i 2020-11-22 14:32

I have an array outside:

$myArr = array();

I would like to give my function access to the array outside it so it can add values to it

6条回答
  •  庸人自扰
    2020-11-22 15:01

    Global $myArr;
    $myArr = array();
    
    function someFuntion(){
        global $myArr;
    
        $myVal = //some processing here to determine value of $myVal
        $myArr[] = $myVal;
    }
    

    Be forewarned, generally people stick away from globals as it has some downsides.

    You could try this

    function someFuntion($myArr){
        $myVal = //some processing here to determine value of $myVal
        $myArr[] = $myVal;
        return $myArr;
    }
    $myArr = someFunction($myArr);
    

    That would make it so you aren't relying on Globals.

提交回复
热议问题