PHP variable scope study notes sharing_PHP tutorial
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 | ||||
function 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
■.$_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 } assignx(); printf("$x outside of function is %d $ inside function is 0 $ outside of function is 4 |
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 | ||||
$value= $value=$value*10 return $value; } |
代码如下 | 复制代码 |
$a = 1; |
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() |
Use $GLOBALS instead of global
The code is as follows | Copy code | ||||
|
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']; } ?> |
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 | ||||||||
$count++; echo $count; if ($count Test ();
} ?> |
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.
代码如下 | 复制代码 |
$url = "www.bKjia.c0m";
$url = "www.bKjia.c0m"; |
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; } ?> |
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(); ?> |
_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
|
Copy code | ||||
function _DisplayUrl()
{
global $myName;
$myName='yibin'; }
_DisplayUrl();
echo $myName; //output yibin
?>
http: //www.bkjia.com/PHPjc/632648.html

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 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 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 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.

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 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.

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

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.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools