PHP 变量通过引用传递

Sheeraz Gul 2022年7月18日
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
Author: Sheeraz Gul
Sheeraz Gul avatar Sheeraz Gul avatar

Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

LinkedIn Facebook

相关文章 - PHP Variable