Home Backend Development PHP Tutorial PHP variable scope study notes sharing_PHP tutorial

PHP variable scope study notes sharing_PHP tutorial

Jul 13, 2016 am 10:50 AM
php and Scope use function share variable exist study notes page

Variable scope refers to whether a variable can be used with each other between pages and functions. What is its scope of action? Let me introduce some study notes of PHP variable usage scope to share with you.

The scope of variables in php is described in the php manual

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. For example:

The code is as follows Copy code
 代码如下 复制代码

$a = 1; /* global scope */

function Test()
{
echo $a; /* reference to local scope variable */
}

Test();
?>

$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 have noticed that PHP’s global variables are a little different from C language. In C language, global variables automatically take effect in functions unless overridden by local variables. Let’s start with the above. Let me introduce it in detail below

Variables in PHP mainly include: built-in super global variables, general variables, constants, global variables, static variables, etc.

■Built-in super global variables can be used and visible anywhere in the script. That is, if we change one of the values ​​in a PHP page, its value will also change when used in other PHP pages.
■Constants once declared will be globally visible, that is, they can be used inside and outside functions, but this is only limited to one page (including PHP scripts we include through include and include_once), but in other pages Can no longer be used.
■Global variables declared in a script are visible throughout the script, but not inside the function. If the variable inside the function has the same name as the global variable, the variable inside the function shall prevail.
■When the variables used inside the function are declared as global variables, their names must be consistent with the names of the global variables. In this case, we can use the global variables outside the function in the function, so as to avoid the previous problem. The variable inside the function has the same name as the external global variable and overrides the external variable.
■Variables created and declared as static inside a function cannot be visible outside the function, but the value can be maintained during multiple executions of the function. The most common situation is during the recursive execution of the function.
■Variables created within a function are local to the function and cease to exist when the function terminates.
The complete list of super global variables is as follows:

■.$GOBALS Array of all global variables
■.$_SERVER server environment variable array

■.$_POST Array of variables passed to this script via the POST method

■.$_GET Array of variables passed to this script via the GET method

■.$_COOKIE cookie variable array
 代码如下 复制代码

$x=4;

function assignx(){

$x=0;

printf("$x inside function is %d
",$x);

}

assignx();

printf("$x outside of function is %d
",$x);

 
执行结果为

$ inside function is 0

$ outside of function is 4

■.$_FILES Array of variables related to file upload ■.$ENV environment variable array ■.$_REQUEST All user-input variable arrays include the input content contained in $_GET $_POST $_COOKIE ■.$_SESSION session variable array 1. Local variables A variable declared in a function is considered a local variable, that is, it can only be referenced within the function. If copied outside a function, it is considered a completely different variable (that is, different from the one contained in the function). Note that when you exit the function in which the variable was declared, the variable and its corresponding value are destroyed.
The code is as follows Copy code
$x=4; function assignx(){ $x=0; printf("$x inside function is %d
",$x); } assignx(); printf("$x outside of function is %d
",$x); The execution result is $ inside function is 0 $ outside of function is 4

2. Function parameters

PHP, like other programming languages, any function that accepts parameters must declare these parameters in the function header. Although these parameters (value parameters) accept values ​​from outside the function, they are no longer accessible after exiting the function.

The code is as follows Copy code
 代码如下 复制代码

function x10($value){
$value=

$value=$value*10

return $value;

}

function x10($value){

$value=

$value=$value*10

return $value;

}

Remember that although these function parameters can be accessed and manipulated within the function in which they are declared, the parameters will be destroyed when the function execution ends.
 代码如下 复制代码

 

$a = 1;
$b = 2;
function Sum()
{
$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];
}
Sum();
echo $b;
?>

3. Global variables

Global variables can be accessed anywhere in the program. However, in order to modify a global variable, it must be explicitly declared as a global variable in the function that modifies the variable. As long as the keyword GLOBAL is added in front of the variable, it is a global variable. If you put the GLOBA keyword in front of an existing variable, it tells PHP to use the variable with the same name.

 代码如下 复制代码

 

function test_global()
{
// 大多数的预定义变量并不 "super",它们需要用 'global' 关键字来使它们在函数的本地区域中有效。
global $HTTP_POST_VARS;
print $HTTP_POST_VARS['name'];
// Superglobals 在任何范围内都有效,它们并不需要 'global' 声明。Superglobals 是在 PHP 4.1.0 引入的。
print $_POST['name'];
}
?>

Use $GLOBALS instead of global

The code is as follows Copy code


$a = 1;

代码如下 复制代码

function Test ()
{
$a = 0;
echo $a;
$a++;
}
?>

$b = 2; function Sum() { $GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"]; } Sum(); echo $b; ?> In the $GLOBALS array, each variable is an element, the key name corresponds to the variable name, and the value variable content. $GLOBALS exists in the global scope because $GLOBALS is a superglobal variable. The following example shows the use of superglobal variables: Example 12-3. Example demonstrating superglobal variables and scope
The code is as follows Copy code
function test_global()<🎜> {<🎜> // Most predefined variables are not "super", they require the 'global' keyword to make them available in the local scope of the function. <🎜> global $HTTP_POST_VARS;<🎜> Print $HTTP_POST_VARS['name'];<🎜> // Superglobals are valid in any scope, they do not require a 'global' declaration. Superglobals were introduced in PHP 4.1.0. <🎜> Print $_POST['name'];<🎜> }<🎜> ?>
Use static variables Another important feature of variable scope is static variables. Static variables only exist in the local function scope, but their values ​​are not lost when program execution leaves this scope. Take a look at the example below: Example 12-4. Demonstrates the need for static variables
The code is as follows Copy code
function Test ()<🎜> {<🎜> $a = 0;<🎜> echo $a;<🎜> $a++;<🎜> }<🎜> ?>


This function is not very useful because it sets the value of $a to 0 and prints "0" every time it is called. $a++, which increments a variable by one, has no effect because the variable $a no longer exists once this function exits. To write a counting function that does not lose the current count value, define the variable $a as static:
Example 12-5. Example of using static variables

function Test()
{
static $a = 0;
echo $a;
$a++;
}
?>


Now, each call to the Test() function will output the value of $a and increment it by one.
Static variables also provide a way to handle recursive functions. A recursive function is a function that calls itself. Be careful when writing recursive functions, as they may recurse indefinitely. You must ensure that there are adequate ways to terminate recursion. Consider this simple function that recursively counts to 10, using the static variable $count to determine when to stop:
Example 12-6. Static variables and recursive functions

The code is as follows Copy code
 代码如下 复制代码

 

function Test()
{
static $count = 0;
$count++;
echo $count;
if ($count < 10) {
Test ();
}
$count--;
}
?>


function Test()

{
代码如下 复制代码

function foo(){
static $int = 0; // correct
static $int = 1+2; // wrong (as it is an expression)
static $int = sqrt(121); // wrong (as it is an expression too)
$int++;
echo $int;
}
?>

static $count = 0;

$count++; echo $count; if ($count < 10) {

Test ();

}
$count--;

}

?>


Note: Static variables can be declared as in the above example. Assigning it with the result of an expression in a declaration will result in a parsing error.

Example 12-7. Declare static variables
 代码如下 复制代码

 

$url = "www.bKjia.c0m";
function _DisplayUrl()
{
echo $url;
}
function DisplayUrl()
{
global $url;
echo $url;
}
_DisplayUrl();
DisplayUrl();
?> 

$url = "www.bKjia.c0m";
function _DisplayUrl()
{
echo $url;
}
function DisplayUrl()
{
global $url;
echo $url;
}
_DisplayUrl();
DisplayUrl();
?>

The code is as follows Copy code
function foo(){<🎜> static $int = 0; // correct<🎜> static $int = 1+2; // wrong (as it is an expression)<🎜> static $int = sqrt(121); // wrong (as it is an expression too)<🎜> $int++;<🎜> echo $int;<🎜> }<🎜> ?>
Note that a friend asked me about global static variables. There is no such thing as global variables in php php is an interpreted language. Although it has the static modifier, its meaning is completely different from that in .Net. Even if a variable in the class is declared static, this variable is only valid in the current page-level application domain. 2. Understand variable scope. Variables declared outside the method cannot be accessed within the method body. Such as:
The code is as follows Copy code
$url = "www.bKjia.c0m"; <🎜> function _DisplayUrl() <🎜> {  <🎜> echo $url; <🎜> }  <🎜> function DisplayUrl() <🎜> {  <🎜> global $url; <🎜> echo $url; <🎜> }  <🎜> _DisplayUrl(); <🎜> DisplayUrl(); <🎜> ?> $url = "www.bKjia.c0m";<🎜> function _DisplayUrl()<🎜> {<🎜> echo $url;<🎜> }<🎜> function DisplayUrl()<🎜> {<🎜> global $url;<🎜> echo $url;<🎜> }<🎜> _DisplayUrl();<🎜> DisplayUrl();<🎜> ?>
The

_DisplayUrl method will not display any results because the variable $url is inaccessible in the method body _DisplayUrl. Just add global before $url, such as the DisplayUrl method.

Global variables defined in the method body can be accessed outside the method:

The code is as follows
 代码如下 复制代码


function _DisplayUrl()
{
global $myName;
$myName='yibin';
}

_DisplayUrl();
echo $myName; //output yibin
?> 

Copy code

function _DisplayUrl()

global $myName;
        $myName='yibin';                                                  } 
         
_DisplayUrl();
echo $myName; //output yibin
?>

http://www.bkjia.com/PHPjc/632648.htmlwww.bkjia.comtrue
http: //www.bkjia.com/PHPjc/632648.html
TechArticle
Variable scope is whether a variable can be used with each other between the page and the function. What is its scope? The editor below will introduce to you some study notes on the use of php variables...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Quick Guide CakePHP Quick Guide Sep 10, 2024 pm 05:27 PM

CakePHP is an open source MVC framework. It makes developing, deploying and maintaining applications much easier. CakePHP has a number of libraries to reduce the overload of most common tasks.

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

See all articles