PHP - declare a global array

烂漫一生 提交于 2020-02-24 12:32:45

问题


I am having a problem of Undefined variable when I try to use an array inside a function. An example is the code below. How can I be able to access the array $prev inside the function hello()? I've tried searching but I don't really know how to use $GLOBALS[$varname] when the variable is an array. Thanks for any help!

<?php

$prev = [0,1,2];

function hello(){

    echo $prev[1];

}

hello();
hello();
hello();

?>

回答1:


You can also pass the variable into the function:

$prev = [0,1,2];

function hello(array $array){

    echo $array[1];

}

hello($prev);
hello($prev);
hello($prev);

?>

An other way is to pass the variable by reference.

function hello(&$array){

    $array[1]++;
    echo $array[1];

}



回答2:


This is the way to use it as global. Btw there are also other ways to use it inside the hello function.

$prev = [0,1,2];

function hello(){
    global $prev;

    echo $prev[1];

}

hello();
hello();
hello();



回答3:


You could do something like:

$GLOBALS["prev"] = [0,1,2];
function hello(){    
    echo $GLOBALS['prev'][1];    
}

hello();

However consider doing something like:

 $prev = [1,2,3];
 function hello($prev) {
      echo $prev[1];
 }
 hello($prev);

As an alternative solution:

class GlobalsContainer {
     public static $prev=[1,2,3];
}

function hello() {
     echo GlobalsContainer::$prev[1];
}
hello();



回答4:


Declare array with global keyword inside the function. See it -

<?php

    function hello(){

        global $prev = [0,1,2];
        echo $prev[1];

    }


    ?>


来源:https://stackoverflow.com/questions/42393222/php-declare-a-global-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!