首頁  >  文章  >  後端開發  >  PHP引用(&)案例介紹

PHP引用(&)案例介紹

尚
轉載
2020-02-21 17:57:082126瀏覽

PHP引用(&)案例介紹變數引用

案例:

<?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;
}

結論

PHP 的變數引用相當於不同的變數都指向同一個內容。也會操作這份內容,如果刪除其中一個引用,另外一個引用不受影響,相當與刪除的變數不在指向同一個內容,但是不能為常數。 (相當於一個人有好多個名字,及時去掉一個名字,也不會影響人這個實體)

推薦:php訓練    

函數引用回傳

案例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;   
}

案例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

結論:

相當於$t = &test; 說白了還是變數之間的引用。

物件引用

案例:

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

引用,其實就是變數空間,賦予了多個運算名稱,這些運算名稱,都指向同一個操作空間,其中一個操作名稱對其空間操作,其他操作名稱得到的結果也會改變。

引用的作用:

#一般來說,每次宣告一個變量,其就會佔用一定的空間。

函數傳參的方便,直接修改原有空間的內容,同時也減少中間變數的空間的開銷。

更多php相關知識請關注php免費培訓網站。

以上是PHP引用(&)案例介紹的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:csdn.net。如有侵權,請聯絡admin@php.cn刪除