HOWTO · PHP

PHP 變數通過引用傳遞

本教程演示如何在 PHP 中通過引用傳遞變數。

本頁內容

變數預設按值傳遞給函式,但在 PHP 中也可以通過引用傳遞。本教程演示如何在 PHP 中通過引用傳遞。

PHP 變數通過引用傳遞

& 符號 & 將新增到變數引數的開頭,以便在 PHP 中通過引用傳遞變數。例如,function(&$a),其中 global 和 function 的變數目標都是成為全域性值,因為它們是使用相同的引用概念定義的。

每當全域性變數發生變化時,函式內部的變數也會發生變化,反之亦然。通過引用傳遞的語法是:

function FunctionName(&$Parameter){
//
}

其中 FunctionName 是函式的名稱,Parameter 是一個將通過引用傳遞的變數。這是一個在 PHP 中通過引用傳遞的簡單示例。

<?php
function Show_Number(&$Demo){
    $Demo++;
}
$Demo=7;
echo "Value of Demo variable before the function call :: ";
echo $Demo;
echo "<br>";
echo "Value of Demo variable after the function call :: ";
Show_Number($Demo);
echo $Demo;
?>

上面的程式碼在函式 Show_Number 中通過引用傳遞變數 Demo。見輸出:

Value of Demo variable before the function call :: 7
Value of Demo variable after the function call :: 8

讓我們嘗試另一個示例,以使用和不使用 & 符號通過引用傳遞。參見示例:

<?php
// Assigning the new value to some $Demo1 variable and then printing it
echo "PHP pass by reference concept :: ";
echo "<hr>";
function PrintDemo1( &$Demo1 ) {
    $Demo1 = "New Value \n";
    // Print $Demo1 variable
    print( $Demo1 );
    echo "<br>";
}
// Drivers code
$Demo1 = "Old Value \n";
PrintDemo1( $Demo1 );
print( $Demo1 );
echo "<br><br><br>";


echo "PHP pass by reference concept but exempted ampersand symbol :: ";
echo "<hr>";
function PrintDemo2( $Demo2 ) {
    $Demo2 = "New Value \n";
    // Print $Demo2 variable
    print( $Demo2 );
    echo "<br>";
}
// Drivers code
$Demo2 = "Old Value \n";
PrintDemo2( $Demo2 );
print( $Demo2 );
echo "<br>";

?>

上面的程式碼建立了兩個用於更改變數值的函式。當變數通過與符號&的引用傳遞時,該函式被同時呼叫並更改變數的值。

類似地,當通過不帶 & 符號的引用傳遞時,它需要呼叫函式來更改變數的值。見輸出:

PHP pass by reference concept ::
New Value
New Value


PHP pass by reference concept but exempted ampersand symbol ::
New Value
Old Value