By default in most assignments, PHP uses assignment by value. When a variable is assigned value from another variable, the latter's value is assigned to the former.
$breakfast = "eggs";
$lunch = $breakfast; // Assignment by value
// Print meals. Outputs:
// eggs
// eggs
echo $breakfast . "\n";
echo $lunch . "\n";
$lunch = "crispy pata";
// Print meals. Outputs:
// eggs
// crispy pata
echo $breakfast . "\n";
echo $lunch . "\n";
Assignment by reference means assigning a reference instead of a value. This results in multiple variables behaving as one.
$breakfast = "eggs";
$lunch = &$breakfast; // Assignment by reference
// Print meals. Outputs:
// eggs
// eggs
echo $breakfast . "\n";
echo $lunch . "\n";
$lunch = "crispy pata";
// Print meals. Outputs:
// crispy pata
// crispy pata
echo $breakfast . "\n";
echo $lunch . "\n";
To understand assignment by reference, it is necessary to have a mental image of how the computer stores data. Variables don't actually contain the data but rather they only hold the "address" of data in computer memory.
When the computer reads the instruction $lunch = $breakfast
, it interprets it as "assign the value of $breakfast
to $lunch
". The computer does this by allocating a new cell in memory to the new variable $lunch
then copying the value of $breakfast
at cell A1
over to $lunch
at cell A3
.
When the value of $lunch
was modified, this actually meant the value of the memory cell with address A3
was modified.
On the other hand, when the computer reads the instruction $lunch &= $breakfast
, it actually reads it as "assign the address of $breakfast
to $lunch
". The computer then shares the address of $breakfast
's memory cell to $lunch
resulting in both of them pointing to the same memory cell.
This time, when the value of $lunch
is modified, it now refers to the value of the memory cell with address A1
. And since both $breakfast
and $lunch
use the same memory cell, both variables will change value when the value in the cell is modified.
In this exercise, your task is to trace some codes and determine the output.
-
What does the following piece of code display?
$a = "foo"; $b = &$a; $b = "Foo"; echo $a;
-
What does the following piece of code display?
$a = "foo"; $b = &$a; $b .= "bar"; echo $a;
-
What does the following piece of code display?
$a = "foo"; $b = &$a; $b .= $a; echo $a;
-
What does the following piece of code display?
$a = "foo"; $b = "bar"; $c = &$a; $d = $b; $a .= $d; $b .= $c; $a .= $b; echo $c;
-
What does the following piece of code display?
$a = "foo"; $b = &$a; $c = "bar"; $b = &$c; echo $a;
- Submit a file with 2 columns:
- Column1: Item number
- Column2: Answer
- Filename must be
exer4-variables3.php
1 Foo
2 100
3 Foobar
4 FizzBuzz
5 Hello world
Gist: https://gist.github.com/czarpino/913e36c4379eb04e5ba425a0e4215802