Detailed introduction to php variable scope

王林
Release: 2023-03-02 10:58:02
forward
2842 people have browsed it

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
Copy after login

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();
Copy after login

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!

Related labels:
source:jb51.net
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template