PHP global Variable Global
Examples of "global" keywords:
The following are the referenced contents:
The following are the referenced contents:
$my _var = ' Hello world ';
Test_global ();
function Test_global () {
Now in the local scope
The $my _var variable doesn ' t exist
Produces error: "Undefined Variable:my_var"
echo $my _var;
Now let ' s important the variable
Global $my _var;
Works:
echo $my _var;
}
? >
As you can see in the above example, the "global" keyword is used to import global variables. It seems to work well and it's simple, so why worry about defining global data with the "global" keyword?
Here are three good reasons:
1, code reuse is almost impossible
If a function relies on global variables, it is almost impossible to use this function in a different environment. Another problem is that you can't extract this function and use it in other code.
2, debugging and solve the problem is very difficult
It is more difficult to track a global variable than to track a non-global variable. A global variable may be redefined in some of the less obvious include files, even if you have a very Good program editor (or IDE) to help you, it will take you several hours to discover the problem.
3, understanding the code will be very difficult things
It's hard to figure out where a global variable comes from and what it does. In the process of development, you may know that every global variable is known, but after about a year, you may forget at least the general global variable, and you will regret the use of so many global variables.
So if we don't use global variables, what should we use? Let's look at some of the solutions below.
Using function arguments
One way to stop using a global variable is simply to pass the variable as a function parameter, as shown in the following:
The following are the referenced contents:
The following are the referenced contents:
$var = ' Hello world ';
Test ($var);
function test ($var) {
Echo $var;
}
? >
If you only need to pass a global variable, then this is a very good or even outstanding solution, but what if you have to pass a lot of values?
For example, if we want to use a database class, a program settings class and a user class. In our code, these three classes are used in all components, so they must be passed to each component. If we use the method of function parameters, we have to do this:
The following are the referenced contents:
The following are the referenced contents:
$db = new DbConnection;
$settings = new Settings_xml;
$user = new User;
Test ($db, $settings, $user);
Function test (& $db, & $settings, & $user) {
Do something
}
? >