PHP/Language Basics/Variable Reference
Содержание
- 1 $b is assigned a copy of $a, and in the second part, $b is assigned a reference to $a.
- 2 Create a reference to a variable with the name of the constant"s value.
- 3 Only named variables may be assigned by reference.
- 4 & operator creates a reference
- 5 Passing arrays by reference
- 6 Passing by Reference in PHP
$b is assigned a copy of $a, and in the second part, $b is assigned a reference to $a.
<source lang="html4strict">
<?php $a = 5; $b = $a; $a = 7; echo "\$a = $a and \$b = $b\n";
$a = 5; $b = &$a; $a = 7; echo "\$a = $a and \$b = $b\n"; ?>
</source>
Create a reference to a variable with the name of the constant"s value.
<source lang="html4strict">
<?php define("CONST_A", "test"); ${CONST_A} = 27; echo "\$test = $test\n"; ?>
</source>
Only named variables may be assigned by reference.
<source lang="html4strict">
<?php
$foo = 25; $bar = &$foo; // This is a valid assignment. function test() { return 25; } $bar = &test(); // Invalid.
?>
</source>
& operator creates a reference
<source lang="html4strict">
<?php $a = 5; $b = $a; $a = 7; echo "\$a = $a and \$b = $b\n"; $a = 5; $b = &$a; $a = 7; echo "\$a = $a and \$b = $b\n"; ?>
</source>
Passing arrays by reference
<source lang="html4strict">
<?
function load_member_data($ID, &$member) { $member["Name"] = "Bob"; return true; } $ID = 1; $result = load_member_data($ID, $member); if ($result) { print "Member {$member["Name"]} loaded successfully.\n"; } else { print "Failed to load member #$ID.\n"; }
?>
</source>
Passing by Reference in PHP
<source lang="html4strict">
<?php
function reference_test($var, &$result, &$result2) { $result = "This is return value #1"; $result2 = "You entered $var as your parameter"; return 42; } $res = reference_test(10, &$res1, &$res2); echo "The value of \$res is "$res"
"; echo "The value of \$res1 is "$res1"
"; echo "The value of \$res2 is "$res2"
";
?>
</source>