Home Backend Development PHP Problem What are the differences between passing by value and passing by reference in PHP?

What are the differences between passing by value and passing by reference in PHP?

Oct 30, 2020 pm 05:12 PM
php Pass value Pass reference

Passing value means copying the value of a variable to a new value; within the function scope, changing the value of the variable will not affect the value of the variable outside the function. Passing by reference copies the reference of the variable; within the function scope, any changes to the value are also reflected outside the function, because passing by reference passes the memory address.

What are the differences between passing by value and passing by reference in PHP?

Recommendation: "PHP Video Tutorial"

php value passing: in function scope Changing the variable value inside the function will not affect the variable value outside the function.

PHP By reference: Within the function scope, any changes to the value are also reflected outside the function, because the memory address is passed by reference.

The difference between passing by value, passing by reference, and passing address:

1. Passing by value is to assign the value of the actual parameter to the line parameter

Then the modification of the row parameter will not affect the value of the actual parameter

2. Passing the address

is a special way of passing the value, but what it passes is the address, not the ordinary one. int

After passing the address, the actual parameters and line parameters point to the same object

3. Passing the reference

Really pass the parameters by address

After passing, the row parameters and actual parameters are the same object, but their names are different

Modification of the row parameters will affect the value of the actual parameters

Daniel's Explanation:

Pass value: It is the same as copy. [For example, I have a house. I give you building materials. You build a house that is exactly the same as mine. Whatever you do in your house will not affect me. What I do in my house will not affect me. Nothing will affect you, independent of each other. 】

<?php 
$testa=1; //定义变量a 
$testb=2; //定义变量b 
$testb = $testa; //变量a赋值给变量b 
echo $testb; //显示为1 
?>
Copy after login

Passing by reference: Similar to pointers in C language, it feels almost the same. For example, I have a house. If I give you a key, both of us can enter the house. Whatever you do in the house will affect me.

[Advantages and Disadvantages:] Passing values ​​will be time-consuming, especially for large strings and objects. This will be a very expensive operation. Transferring references is equivalent to any operation within the function. For operations on transfer variables, it is highly efficient when transferring large variables!

1. Let’s explain the noun first.

During the value transfer (passl-by-value) process, the formal parameters of the called function are treated as local variables of the called function, that is, a memory space is opened in the stack to store the parameters put in by the calling function. The value of the actual parameter becomes a copy of the actual parameter. The characteristic of value transfer is that any operation of the called function on the formal parameters is performed as a local variable and will not affect the value of the actual parameter variable of the calling function.

During the pass-by-reference process, although the formal parameters of the called function are also used as local variables to open up memory space on the stack, what is stored at this time is put in by the calling function. The address of the actual parameter variable. Any operation of the called function on the formal parameters is processed as indirect addressing, that is, the actual parameter variables in the calling function are accessed through the address stored in the stack. Because of this, any operation the called function does on the formal parameters affects the calling function.

Note: The red text above explains that application transfer does not open up space, but does open up space, but the space opened up is used to store the actual parameter variable address.

2.php has the following three usages.

①. Reference assignment of variables: $a = &$b

②. Reference parameter passing when calling function

1) In the early days of PHP, the & symbol was used when calling Pass reference type variables, such as: func(&$arg);

2) Later, the reference type parameters of functions were stipulated to need to be defined when the function is declared, instead of: function func(&$arg);

Note:After defining reference type parameters during reference declaration, runtime reference parameter passing is abandoned. You need to add allow_call_time_pass_reference to php.ini to enable it.

③. The function returns a reference type. This application method requires adding an & symbol before the function name when declaring the function, and when calling, the reference assignment method must be used. The example code is as follows:

function &func() {
    return $a;
}
$a = func();  //这种调用方式得到的不是引用传值
$a =& func(); //这样调用才是引用传值
Copy after login
$a = 1;
function &func(&$a) {
  return $a;
}
$b = func($a);
$c =& func($a);
$b = 2;
echo "a: $a, b: $b, c: $c. <br />/n";
//输出a: 1, b: 2, c: 1.
//可见对$b的修改不会影响$a
$c = 3;
echo "a: $a, b: $b, c: $c. <br />/n";
//输出a: 3, b: 2, c: 3.
//可见对$c的修改会影响$a
Copy after login

Please see the detailed example below :

3.php Various data types pass value/pointer

1. Value pass of basic data types

/* **************************************************** */ 
function testvar($k){
 $k = 40;
}
$c = 30;
//给一个函数参数传一个基本数据类型(整型,布尔,字符 ...), 实际上传的就是值 ;
testvar($c);
echo $c;//结果是:30
function testvar2(&$k){
 $k = 40;
}
$e = 30;
//给一个函数参数传一个基本数据类型(整型,布尔,字符 ...), 实际上传的y就是地址 ;
testvar2($e);
echo $e;//结果是:40
  
/* **************************************************** */
Copy after login

2. Array (by default, a copy of the data is copied), if you want to pass the address, then &$arr

 1 $arr1 = array(-1,5,0); 
 2 function testArr($arr){ 
 3  for($i=0;$i<count ($arr);$i++){ 
 4   for($j=$i+1;$j<count($arr);$j++){ 
 5    if($arr[$i]>$arr[$j]){ 
 6     $temp = $arr[$i]; 
 7     $arr[$i] = $arr[$j]; 
 8     $arr[$j] = $temp; 
 9    } 
10   } 
11  
12  } 
13  print_r($arr);  //结果:Array ( [0] => -1 [1] => 0 [2] => 5 )  
14 } 
15 testArr($arr1); 
16 print_r($arr1);  //结果:Array ( [0] => -1 [1] => 5 [2] => 0 )  
17  
18 function testArr2(&$arr){ 
19  for($i=0;$i</count><count ($arr);$i++){ 
20   for($j=$i+1;$j<count($arr);$j++){ 
21    if($arr[$i]>$arr[$j]){ 
22     $temp = $arr[$i]; 
23     $arr[$i] = $arr[$j]; 
24     $arr[$j] = $temp; 
25    } 
26   } 
27  
28  } 
29 } 
30 testArr($arr1); 
31 print_r($arr1);  //结果:Array ( [0] => -1 [1] => 0 [2] => 5 )
Copy after login

3. Pass value of object data type

class person{
 public $name;
 public  $age;
}
  
$a = new person();
$a->name = &#39;小明&#39;;
$a->age = &#39;20&#39;;
//变量a在存的是对象的地址,把a赋给b这个变量,实际上就是赋了一个地址。
$b = $a;
$b->age = 30;
//echo $a->age.$b->age;//结果是:30 30
//给一个函数参数传一个对象, 实际上传的是这个对象的地址;
function test($k){
 $k->age =40;
}
//调用
test($b);
//echo $a->age.$b->age;//结果是:40 40
Copy after login

In PHP5, object copying is achieved by reference. In the above column, $a=new person; $b=$a; is actually equivalent to $a=new person; $b=&$a;
The default in PHP5 is to call objects by reference, but sometimes you may want to Create a copy of an object and hope that changes to the original object will not affect the copy. For this purpose, PHP defines a special method called __clone.

4.php copy-on-write

php中对于地址的指向(类似指针)功能不是由用户自己来实现的,是由Zend核心实现的,php中引用采用的是“写时拷贝”的原理,就是除非发生写操作,指向同一个地址的变量或者对象是不会被拷贝的。

通俗的讲

1:如果有下面的代码

$a="ABC";
 $b=$a;
Copy after login

其实此时$a与$b都是指向同一内存地址而并不是$a与$b占用不同的内存

2:如果在上面的代码基础上再加上如下代码

$a="EFG";
Copy after login

由于$a与$b所指向的内存的数据要重新写一次了,此时Zend核心会自动判断自动为$b生产一个$a的数据拷贝,重新申请一块内存进行存储。

5.php引用于C指针的区别

在PHP 中引用的意思是:不同的名字访问同一个变量内容.
与C语言中的指针是有差别的.C语言中的指针里面存储的是变量的内容在内存中存放的地址。

PHP 的引用允许你用两个变量来指向同一个内容

$a="ABC";
$b =&$a;
echo $a;//这里输出:ABC
echo $b;//这里输出:ABC
$b="EFG";
echo $a;//这里$a的值变为EFG 所以输出EFG
echo $b;//这里输出EFG
Copy after login

当你 unset 一个引用,只是断开了变量名和变量内容之间的绑定。这并不意味着变量内容被销毁了。例如:

unset($a);
echo $b;//这里输出EFG
Copy after login

相关推荐:php培训

The above is the detailed content of What are the differences between passing by value and passing by reference in PHP?. For more information, please follow other related articles on the PHP Chinese website!

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

Video Face Swap

Video Face Swap

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

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1273
29
C# Tutorial
1253
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 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.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 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.

See all articles