Home >Backend Development >PHP Tutorial >The use of global and php global variables

The use of global and php global variables

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-07-30 13:30:42995browse

PHP’s global variables are different from other programming languages. In most programming languages, global variables automatically take effect in the functions and classes below them, unless they are overridden by local variables, or they are not allowed to be declared with the same name at all. Type of local variables, but global variables in php are not effective by default. Global variables in PHP must be declared global when used in functions. The Global keyword is only useful when defined in functions. In other words, the role of Global is to define global variables, but this global variable does not apply to the entire website, but to the current page, including all files in include or require.

Use an example directly to illustrate this problem, the following code:

<?php
$a=5;
function test(){
	echo $a;
}
test();
?>

It’s very simple, declare a global variable $a=5, then declare a function test() to print this global variable, and then call this test(), According to the general programming language thinking, the output here must be 5. However, in actual execution, it has the following effect:


An error is reported directly. It is simply unreasonable to say that a is not defined, but PHP is set up like this, but I need to use $a as a global variable. There may be many functions and classes below that need to use this $a! This is, you need to declare it with the global keyword every time you use the global variable $a.

The following code is a correct demonstration:

<?php
$a=5;
function test(){
	global $a;
	echo $a;
}
test();
?>
The running results are as follows, so that a can be used. Every time you use the global variable $a, you must declare it like this. This is a PHP rule.

It is worth noting that the following code is wrong:

<?php
global $a;
$a=5;
function test(){
	echo $a;
}
test();
?>
The same is true for the running result:


Copyright statement: This article is an original article by the blogger and may not be reproduced without the blogger's permission.

The above introduces the use of global and the global variables of PHP, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn