search
HomeBackend DevelopmentPHP Tutorial浅谈PHP变量作用域以及地址引用问题_PHP

作用域的概念:

在PHP脚本的任何位置都可以声明变量,但是,声明变量的位置会大大影响访问变量的范围。这个可以访问的范围称为作用域。

主要的常用的包括:局部变量、全局变量、静态变量。

1、局部变量:就是在函数内声明的变量,他保存在内存的栈内,所以访问速度很快。仅在函数内有效。

2、全局变量:与局部变量相反,全局变量可以在程序的任何地方访问。只要在变量前面加关键字GLOBAL,就可以将其识别为全局变量。在整个php文件内有效。

3、静态变量:用static修饰只存在于函数作用域的变量,函数执行结束后其值并不消失。注:初始化后不能再次进行初始化,不能用表达式来赋值。

复制代码 代码如下:
function test()
{
static $b=0;//申明静态变量,放在函数外部声明的话,在函数内部是用不到的

$b=$b+1;

echo $b;
}
test();//这条语句会输出 $b的值 为1
test();//这条语句会输出 $b的值 为2

注:static $b=0 这一赋值操作只会在变量第一次被初始化的时候执行。

附A:类中静态成员和静态方法,差不多只是调用的时候统一使用类名或者self或者parent加::xxx,他们的作用域和这个一样,但是他的声明是在方法外部的

附B:js里面的作用域使:用var aa=‘xxx';在函数外面声明的就是全局变量(不管是否带有修饰符var)。在函数内部使用 var声明的是局部变量,不使用var修饰的是全局变量。

附C:关于引用

PHP引用:就是在变量、函数或者对象前加&.php中的引用就是想用不同的名字访问同一个变量的内容。

1、变量的引用:

复制代码 代码如下:
$a="ABC";

$b =&$a;

echo $a;//这里输出:ABC

echo $b;//这里输出:ABC

$b="EFG";

echo $a;//这里$a的值变为EFG 所以输出EFG

echo $b;//这里输出EFG

2、函数的传址调用

复制代码 代码如下:
function test(&$a)

{

$a=$a+100;

}

$b=1;

echo $b;//输出1

test($b); //这里$b传递给函数的其实是$b的变量内容所处的内存地址,通过在函数里改变$a的值 就可以改变$b的值了

echo "
";

echo $b;//输出101

3、函数的引用返回

复制代码 代码如下:
function &test()
{

static $b=0;//申明一个静态变量

$b=$b+1;

echo $b;

return $b;

}

$a=test();//这条语句会输出 $b的值 为1

$a=5;

$a=test();//这条语句会输出 $b的值 为2

$a=&test();//这条语句会输出 $b的值 为3

$a=5;

$a=test();//这条语句会输出 $b的值 为6

解析:使用$a=test()得到的其实不是函数的引用返回。只是将函数的返回值复制给$a,而不会影响到$b。这样调用和普通的调用没区别。

Php规定:$a=&test()方式得到才是函数的引用返回。他将$b变量的内存地址和$a变量的内存地址指向了同一个地方。即相当于$a=&$b;

4、取消引用

复制代码 代码如下:
$a = 1;

$b =& $a;

unset ($a);

echo $b;

解析:unset一个引用,只是取消了变量名和变量的内容之间的绑定,并不意味着内容被销毁,其值还是真实存在的。

5、global引用:使用global $var  声明一个变量时,其实就是建立了一个到全局变量的引用。Global $val $var=&$GLOBALS[‘var'] ;

6、对象的引用:在对象的方法中,$this调用的对象都是调用它的引用

注:php中对于地址的指向不是由用户自己来实现的,而是通过zend核心实现的,php的引用采用的是“写拷贝”的原理,就是除非发生写操作,指向同一个地址的变量或对象是不会被拷贝的。

复制代码 代码如下:
$a = 1;

$b =$a;

$a和$b都是指向同一个内存地址,并不是$a和$b占用不同的内存。

若是现在执行一句$a=”dsd”:$a和$b所指向的内存数据需要重新写一次,此时zend核心会自动判断。自动为$b产生一个$a的数据拷贝,重新申请一块内存进行存储。

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
PHP vs. Python: Understanding the DifferencesPHP vs. Python: Understanding the DifferencesApr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP: Is It Dying or Simply Adapting?PHP: Is It Dying or Simply Adapting?Apr 11, 2025 am 12:13 AM

PHP is not dying, but constantly adapting and evolving. 1) PHP has undergone multiple version iterations since 1994 to adapt to new technology trends. 2) It is currently widely used in e-commerce, content management systems and other fields. 3) PHP8 introduces JIT compiler and other functions to improve performance and modernization. 4) Use OPcache and follow PSR-12 standards to optimize performance and code quality.

The Future of PHP: Adaptations and InnovationsThe Future of PHP: Adaptations and InnovationsApr 11, 2025 am 12:01 AM

The future of PHP will be achieved by adapting to new technology trends and introducing innovative features: 1) Adapting to cloud computing, containerization and microservice architectures, supporting Docker and Kubernetes; 2) introducing JIT compilers and enumeration types to improve performance and data processing efficiency; 3) Continuously optimize performance and promote best practices.

When would you use a trait versus an abstract class or interface in PHP?When would you use a trait versus an abstract class or interface in PHP?Apr 10, 2025 am 09:39 AM

In PHP, trait is suitable for situations where method reuse is required but not suitable for inheritance. 1) Trait allows multiplexing methods in classes to avoid multiple inheritance complexity. 2) When using trait, you need to pay attention to method conflicts, which can be resolved through the alternative and as keywords. 3) Overuse of trait should be avoided and its single responsibility should be maintained to optimize performance and improve code maintainability.

What is a Dependency Injection Container (DIC) and why use one in PHP?What is a Dependency Injection Container (DIC) and why use one in PHP?Apr 10, 2025 am 09:38 AM

Dependency Injection Container (DIC) is a tool that manages and provides object dependencies for use in PHP projects. The main benefits of DIC include: 1. Decoupling, making components independent, and the code is easy to maintain and test; 2. Flexibility, easy to replace or modify dependencies; 3. Testability, convenient for injecting mock objects for unit testing.

Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Explain the SPL SplFixedArray and its performance characteristics compared to regular PHP arrays.Apr 10, 2025 am 09:37 AM

SplFixedArray is a fixed-size array in PHP, suitable for scenarios where high performance and low memory usage are required. 1) It needs to specify the size when creating to avoid the overhead caused by dynamic adjustment. 2) Based on C language array, directly operates memory and fast access speed. 3) Suitable for large-scale data processing and memory-sensitive environments, but it needs to be used with caution because its size is fixed.

How does PHP handle file uploads securely?How does PHP handle file uploads securely?Apr 10, 2025 am 09:37 AM

PHP handles file uploads through the $\_FILES variable. The methods to ensure security include: 1. Check upload errors, 2. Verify file type and size, 3. Prevent file overwriting, 4. Move files to a permanent storage location.

What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?What is the Null Coalescing Operator (??) and Null Coalescing Assignment Operator (??=)?Apr 10, 2025 am 09:33 AM

In JavaScript, you can use NullCoalescingOperator(??) and NullCoalescingAssignmentOperator(??=). 1.??Returns the first non-null or non-undefined operand. 2.??= Assign the variable to the value of the right operand, but only if the variable is null or undefined. These operators simplify code logic, improve readability and performance.

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

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

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)