Using global vars within a function in PHP the way you do it in Javascript

后端 未结 5 1894
渐次进展
渐次进展 2021-01-27 15:22

I have a function that uses lots of global vars and arrays - e.g.

$a=1;
$b[0]=\'a\';
$b[1]=\'b\';
$c=\'Hello\';

function foo() {
 echo \"$a 
       $b[0] 
              


        
5条回答
  •  半阙折子戏
    2021-01-27 15:38

    Since in PHP you do not have to declare variables before they are used, the following code is ambiguous as to what variable the function is referring to.

    $a = 'ten';
    function foo($a) {
       echo($a);
    }
    
    foo(10); // Outputs: 10
    

    PHP removes the ambiguity by assuming that all variables in the scope of a function are local, unless they are declared in the function to come from the global scope by using the global keyword.

    $a = 10;
    function foo($b) {
        global $a;
        echo($a);
    }
    
    foo('ten'); // Outputs: 10
    

    In general the use of global variables is discouraged since it introduces tight-coupling between your objects, decreases the readability and locality of code, pollutes the global namespace and increases the mental-load on developers having to remember how many/what global variables they have.

提交回复
热议问题