Home  >  Article  >  Backend Development  >  PHP reference (&) case introduction

PHP reference (&) case introduction

尚
forward
2020-02-21 17:57:082168browse

PHP reference (&) case introductionVariable reference

Case:

<?php
//变量单独引用
$test = "a string!\n";
$quote = &$test;

echo $test; //a string!
echo $quote;//a string!

$quote = "exchange!\n";
echo $test; //exchange!
echo $quote;//exchange!

unset($quote);
echo $test; //exchange!

//函数传参引用
$num = 10;
echo $num."\n";
test($num);
echo $num."\n";

function test( &$num) {
    $num += 10;
}

Conclusion

PHP variable reference is equivalent to different variables pointing to the same content . This content will also be operated. If one of the references is deleted, the other reference will not be affected. It is equivalent to the deleted variable no longer pointing to the same content, but it cannot be a constant. (It is equivalent to a person having multiple names. If you remove a name in time, it will not affect the person as an entity)

Recommendation: php training

Function reference Return

Case 1:

<?php

$t = test(); // 1
var_dump($t); // int(1)
$t = 20; $t = test(); //2
var_dump($t); //int(2)
$t = &test(); //3
var_dump($t) ; //int(3)
$t = 20; $t = test(); //21
var_dump($t); //int(21)

function &test() {
    static $test = 0;
    $test += 1;
    echo $test."\n";
    
    return $test;   
}

Case 2:

?php

$t = test();

function &test() {
    static $test = 0;
    $test += 1;
    echo $test."\n";
}


$ php test.php 
1
PHP Notice:  Only variable references should be returned by reference in /home/q/www/zt.dujia.qunar.com/test.php on line 9

Conclusion:

is equivalent to $t = &test; To put it bluntly, it is still one of the variables references between.

Object reference

Case:

<?php
class a{
    var $abc="ABC";
} 
$b=new a; 
$c=$b; 
echo $b->abc;//这里输出ABC 
echo $c->abc;//这里输出ABC
 $b->abc="DEF"; 
echo $c->abc;//这里输出DEF
?>

Reference is actually a variable space that is given multiple operation names. These operation names , all point to the same operation space. If one operation name operates on its space, the results obtained by other operation names will also change.

The role of quotation:

Generally speaking, every time a variable is declared, it will occupy a certain amount of space.

The convenience of function parameter passing can directly modify the content of the original space, while also reducing the space overhead of intermediate variables.

For more knowledge about php, please pay attention to the php free training website.

The above is the detailed content of PHP reference (&) case introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete