- $db _name= "Test";
- $db _username= "root";
- Global $db _password;
- ?>
Copy Code2, Database operation class (call config file) db.fun.php:
- Require ("config/config.php");
- Class db{
- function Fun () {
- Global $db _username, $db _password;
- echo "Database user name:" $db _username. "
";
- echo "Database password:". $db _password. "
";
- }
- }
- ?>
Copy Code3, application file test.php:
- Require ("include/db.fun.php");
- $a = new db ();
- $a->fun ();
- ?>
Copy Code4,global Keywords:
- $a = 1; /* Global scope */
- function Test ()
- {
- echo $a; /* Reference to local scope variable */
- }
- Test ();
- ?>
Copy CodeThis script does not have any output, because the Echo statement refers to a local version of the variable $a, and within that range, it is not assigned a value. PHP has a slightly different global variable from the C language, and in C, global variables are automatically applied in functions unless overridden by local variables. This can cause some problems, and some people may change a global variable. A global variable in PHP must be declared global when used in a function.
- $a = 1;
- $b = 2;
- function Sum ()
- {
- Global $a, $b;
- $b = $a + $b;
- }
- Sum ();
- Echo $b;
- ?>
Copy CodeThe output of the above script will be "3". The global variable $a and $b are declared in the function, and all reference variables of any variable are pointed to the global variable. PHP has no restrictions on the maximum number of global variables a function can declare. |