PHP/Language Basics/Variable Reference

Материал из Web эксперт
Перейти к: навигация, поиск

$b is assigned a copy of $a, and in the second part, $b is assigned a reference to $a.

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



Create a reference to a variable with the name of the constant"s value.

 
<?php 
define("CONST_A", "test"); 
${CONST_A} = 27; 
echo "\$test = $test\n"; 
?>



Only named variables may be assigned by reference.

 
<?php
    $foo = 25;
    $bar = &$foo; // This is a valid assignment.
    
    function test() {
        return 25;
    }
    $bar = &test(); // Invalid.
?>



& operator creates a reference

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



Passing arrays by reference

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



Passing by Reference in PHP

 
<?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"<BR>";
    echo "The value of \$res1 is "$res1"<BR>";
    echo "The value of \$res2 is "$res2"<BR>";
?>