Home > Article > Backend Development > What is the usage of global in php?
The usage of global in php is: 1. If you use global to declare, you can call variables outside the function; 2. Introduce the [$mk] variable outside the function, and global will be globalized here. The meaning of the variable.
The usage of global in php is:
To introduce a variable in java, it can be passed in the form of parameters , because Java uses object-oriented programming, but there are a lot of process-oriented things in PHP. For example, when an external variable is introduced into a function, under normal circumstances, this external variable is not passed in through parameters. , but introduced directly through global. But this global does not mean globalization. It is a test of the code.
$mk ="Test value"; <br> function initValue() <br> { <br> $va =$mk; <br> echo $va; <br> } <br><br>
The running result is:
- Undefined variable: mk
Because $mk
is only defined in the method , so it is a different variable from $mk
defined before the method. $mk
has no value assigned, so an error is reported.
If it is declared with global, you can call variables outside the function.
$mk ="Test value"; <br> function initValue() <br> { <br> global $mk; <br> $va =$mk; <br> echo $va; <br> } <br> initValue(); <br>
The running result is: Test value. Here, global is used to introduce the $mk
variable outside the function.
In order to test global, here There is no meaning of globalizing variables, so I did another test.
$mk ="Test value"; <br> function initValue() <br> { <br> global $mk; <br> $va =$mk; <br> echo $va; <br> } <br> function initValue2() <br> { <br> $vc =$mk; <br> echo $vc; <br> } <br> initValue(); <br> initValue2(); <br>
The running results are: Test value and - Undefined variable: mk, which shows that even if global is used, it is only valid in a function, so the global here is just to introduce the upper variable
Related learning recommendations: PHP programming from entry to proficiency
The above is the detailed content of What is the usage of global in php?. For more information, please follow other related articles on the PHP Chinese website!