The global global environment of php is not measured in include files of class function

  • 2020-07-21 07:18:24
  • OfStack

Test code 1.ES0en
 
<?php 
$g1 = 'g1'; 
class c{ 
function fun() { 
include('2.php'); 
echo "\n-----in class fun---\n"; 
global $g1; 
var_dump("\$g1 => ", $g1 
,'$g2 => ', $g2 
,'$gg2 => ', $gg2 
); 
echo "\n--------\n"; 
} 
} 
c::fun(); 
echo "\n--- in 1.php ----\n"; 
var_dump('$g1 => ', $g1 
,'$g2 => ', $g2 
,'$gg2 => ', $gg2); 
echo "\n--- ----\n"; 

Code 2. php
 
<?php 
$g2 = 'g2'; 
global $gg2;// This environment is not global , Need to increase  
$gg2 = 'gg2'; 
function g2fun() { 
global $g1, $g2, $gg2; 
echo "\n--- in g2fun ----\n"; 
var_dump('$g1 => ', $g1, '$g2 => ', $g2 
, '$gg2 => ', $gg2); 
echo "\n--- ----\n"; 
} 
g2fun(); 
echo "\n--- in 2.php ----\n"; 
var_dump('$g1 => ', $g1, '$g2 => ', $g2 
, '$gg2 => ', $gg2 
); 
echo "\n--- ----\n"; 
global $g1; 
echo "\n--- in 2.php global----\n"; 
var_dump('$g1 => ', $g1, '$g2 => ', $g2 
, '$gg2 => ', $gg2 
); 
echo "\n--- ----\n"; 

The results of
 
--- in g2fun ---- 
string(7) "$g1 => " 
string(2) "g1" 
string(7) "$g2 => " 
NULL 
string(8) "$gg2 => " 
string(3) "gg2" 
--- ---- 
--- in 2.php ---- 
string(7) "$g1 => " 
NULL 
string(7) "$g2 => " 
string(2) "g2" 
string(8) "$gg2 => " 
string(3) "gg2" 
--- ---- 
--- in 2.php global---- 
string(7) "$g1 => " 
string(2) "g1" 
string(7) "$g2 => " 
string(2) "g2" 
string(8) "$gg2 => " 
string(3) "gg2" 
--- ---- 
-----in class fun--- 
string(7) "$g1 => " 
string(2) "g1" 
string(7) "$g2 => " 
string(2) "g2" 
string(8) "$gg2 => " 
string(3) "gg2" 
-------- 
--- in 1.php ---- 
string(7) "$g1 => " 
string(2) "g1" 
string(7) "$g2 => " 
NULL 
string(8) "$gg2 => " 
string(3) "gg2" 
--- ---- 

So you can see,
After include in class, the variable field of include file has become func, not global.
But you can ascend through global.
When include files are generally written, they may feel a little depressed because they don't notice being include.

Related articles: