search
HomeBackend DevelopmentPHP Tutorial变量的活动范围_PHP

变量的活动范围_PHP

Jun 01, 2016 pm 12:39 PM
testoverall situationfunctionvariableActivityscope

变量的活动范围仅仅限于定义它的上下文。对于绝大多数部分中所有的PHP变量仅仅只有单独的活动范围。然而,在用户自定义的函数中,引入了一个本地函数范围的概念。在这个函数中使用的任何变量缺省被限制在该函数的本地函数范围之中。例如:

 

$a = 1; /* global scope */

Function Test () {

echo $a; /* reference to local scope variable */ }

Test ();

 

这段脚本将不会造成任何的输出,因为给显示的提交给本地译文的变量“$a”的申明,同时这个变量没有在它的活动范围中被指定一个值。您可以注意到这和C语言有一些不同,在C语言中全局变量是自动被设定为可用的,除非在函数中进行了特别的说明。由于人们可能会不小心的改变了全局变量的值,所以这可会在程序中导致许多问题。在PHP中全局变量必须在一个函数中被公告,如果想要在这个函数中使用它的话。例子如下:

 

$a = 1;

$b = 2;

Function Sum () {

global $a, $b;

$b = $a + $b;

}

Sum ();

echo $b;

 

上面的脚本将输出“3”。在函数中申明了全局变量$a和$b,任何对这两个变量的引用都被指定到了该全局变量。这里没有函数可以操作的限制全局变量的数目。

第二种接受全局变量的方法是使用PHP特殊的定义数组$GLOBALS,例子如下所示:

$a = 1;

$b = 2;

Function Sum () {

$GLOBALS["b"] = $GLOBALS["a"] + $GLOBALS["b"];

}

Sum ();

echo $b;

 

$GLOBALS数组是一个联合数组使用“global”为变量的名字,全局变量作为该变量数组其中某个元素的值。

另一个关于变量活动范围的重要特性是“静态变量”。一个静态变量仅仅在本地函数的活动范围中存在,但是当程序离开这个范围时,它的值并不丢失。请参考下面的例子:

 

Function Test () {

$a = 0;

echo $a;

$a++;

}

 

这个函数每次被调用时都把变量$a置为0同时打印“0”,所以几乎是没有作用的。表达式“$a++”将增加变量的值,但是每次退出函数时变量$a就消失了。想要使用一个不丢失当前计算的记数函数,用户可以将变量$a设置为静态的,示例如下:

 

Function Test () {

static $a = 0;

echo $a;

$a++;

}

 

现在,每一次当Test()函数被调用的时候,它将打印出变量$a和它当时增加之后的数值。

  当函数被递归调用的时候,使用静态变量是一种很重要的方法。递归函数就是可以调用自身的函数。当编写递归函数的时候,必须注意可能会发生的循环定义。您必须有一个适当的方法来中断这个递归过程。下面的例子递归了10次:

 

Function Test () {

static $count = 0;

$count++;

echo $count;

if ($count
Test (); }

$count--;

}






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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

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 Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software