Home  >  Article  >  Backend Development  >  Detailed introduction to php variable scope

Detailed introduction to php variable scope

王林
王林forward
2020-07-10 17:21:042651browse

Detailed introduction to php variable scope

After a variable is defined, by default, it can be used within the function, but not outside the function.

(Recommended learning: php tutorial)

  • Variables can only be used within their scope. This scope is called the variable's scope. Scope

  • Variables defined in a function are called local variables

  • Variables defined outside the function are called global variables

Code example:

function test (){
    $sum = 36; //局部变量
    return $sum;
}
$sum = 0;	//全局变量
echo text();	//输出结果:36
echo $sum;	//输出结构:0

So how to use global variables in functions?

Parameter passing, global keyword and super global variable $GLOBALS.

Code example:

$snap = 'nihao';
function abc(){
 global $snap;//全局变量的关键词,通常加在变量前。引用全局变量
 return $GLOBALS['snap'];//引用外部变量。定义全局变量
}
echo abc();

The above is the detailed content of Detailed introduction to php variable scope. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete