Home  >  Article  >  Backend Development  >  PHP global variable scope analysis_PHP tutorial

PHP global variable scope analysis_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:45:08782browse

Copy code The code is as follows:

$a = 1;
include 'b.inc' ;
?>

This variable $a will take effect in the include file b.inc. However, in user-defined functions, a local function scope will be introduced. Any variables used inside a function will be restricted to the local function scope by default.
Copy code The code is as follows:

$a = 1; /* global scope */
function Test ()
{
echo $a ; /* reference to local scope variable */
}
Test ();
?>

This script will produce no output because the echo statement refers to a local version of the variable $a, and it is not assigned a value within this scope. You may notice that global variables in PHP are a little different from C language
Global variables in PHP must be declared as global (global keyword) when used in functions
Copy code The code is as follows:

$a = 1;
$b = 2;
function Sum ()
{
global $a , $b ;
$b = $a + $b ;
}
Sum ();
echo $b ;
?>

The output of the above script will be "3".

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/320427.htmlTechArticleCopy the code as follows: ?php $a = 1; include 'b.inc'; ? The variable $a here Will take effect in the include file b.inc. However, in a user-defined function, a local function scope will...
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