Читать книгу PHP Programming for Beginners. Key Programming Concepts. How to use PHP with MySQL and Oracle databases (MySqli, PDO) - Sergey D Skudaev - Страница 9

Passing parameters by value or by reference

Оглавление

At run time, the system assigns our declared variable to a memory location called a reference.

The reference to a variable can be accessed by preceding the identifier of a variable with an ampersand sign (&). The variable address is a hexadecimal number. As seen displayed in the following C++ code, on the first line we declare a pointer (*a) to a memory address. On the second line, we declare a variable (b) and assign its address to the pointer (a). And finally, on the last line, the content of the address of the memory location is displayed as a hexadecimal number.


int *a;

int b=7;

a = &b;


cout <<“The address of the memory location of b:"<<a <<endl;


Output: The address of the memory location of b: 0039FF15


In PHP you can pass the variable address to a function by preceding its name with an ampersand (&). Normally, when we pass a variable to a function, by default the system makes a copy of the variable and passes the copy to the function. The value of the copy may change inside the function, but the value of the original variable remains the same.

As reflected in the two examples below, when passing a variable by reference, the address of the variable is passed inside the function. So, if a new value is assigned to the address, the value of the original variable changes as well. In the first example, we pass variables by values; and in the second, we pass them by reference.

<?php


function switch_by_value ($k, $n) {


$temp=0;

$temp=$k;

$k=$n;

$n=$temp;

}


$a = 5;

$b= 7;

echo “By Value: <br>”;

echo “Before: a=”. $a. ' b=”. $b.”<br>”;


switch_by_value ($a, $b);


echo “After: a=”. $a. ' b=”. $b.”<br>”;


Output:

By Value:

Before: a=5 b=7

After: a=5 b=7


Notice that the values of the original variables (a) and (b) are not switched.


function switch_by_reference (&$k, &$n) {


$temp=0;

$temp=$k;

$k=$n;

$n=$temp;

}


$a = 5;

$b= 7;

echo “By Reference: <br>”;


echo “Before: a=”. $a. ' b=”. $b.”<br>”;


switch_by_reference ($a, $b);


echo “After: a=”. $a. ' b=”. $b;


?>


Output:

By Reference:

Before: a=5 b=7

After: a=7 b=5


Notice that the values of the original variables (a) and (b) are switched.

PHP Programming for Beginners. Key Programming Concepts. How to use PHP with MySQL and Oracle databases (MySqli, PDO)

Подняться наверх