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

后端 未结 5 1861
渐次进展
渐次进展 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:33

    You can access global vars with global keyword:

    global $a=1;
    global $b[0]='a';
    global $b[1]='b';
    global $c='Hello';
    
    function foo() {
      global $a, $b, $c;
      echo "$a 
      $b[0] 
      $b[1] 
      $c";
     }
    

    Otherwise you can use predefined $GLOBALS array:

    function foo() {
     echo "$GLOBALS['a'] 
     $GLOBALS['b'][0] 
     $GLOBALS['b'][1] 
     $GLOBALS[c]";
    }
    

    Here you have more info:

    http://php.net/manual/en/language.variables.scope.php

提交回复
热议问题