Understanding References in PHP: Variables, Function Parameters, and Return Values
This article explains how PHP references let multiple variables share the same value, covering variable references, passing arguments by reference, returning references from functions, and using references with object properties, accompanied by clear code examples.
PHP references allow two different names to access the same variable content, which differs from C pointers that store memory addresses.
Variable reference : assigning one variable to another by reference makes them point to the same value, so changes to either affect both.
<?php
$a = 'abc';
$b = &$a;
var_dump($a, $b); // both 'abc'
$b = 123;
var_dump($a, $b); // both 123Function parameter reference passing (call‑by‑reference) : when a function parameter is declared with & , the argument’s memory address is passed, allowing the function to modify the original variable.
<?php
function test(&$a){
$a = $a + 100;
}
$b = 1;
test($b);
var_dump($b); // int(101)When using call_user_func_array , the argument must also be prefixed with & to be passed by reference.
<?php
function test(&$a){
$a = $a + 10;
}
$b = 1;
call_user_func_array('test', array(&$b));
var_dump($b); // int(11)Function reference return : a function can return a reference, allowing the caller to bind a variable directly to the function’s internal variable.
function &test(){
static $b = 0; // static variable
$b = $b + 1;
echo $b; // prints current value
return $b;
}
$a = test(); // $a gets value 1
$a = 5;
$a = test(); // $a gets value 2
$a = &test(); // $a becomes a reference to $b, now 3
$a = 5;
$a = test(); // $a gets value 6Returning references is often used with object properties. The following example shows a class method returning a reference to a private property, enabling external code to modify it directly.
class talker{
private $data = 'Hi';
public function &get(){
return $this->data;
}
public function out(){
echo $this->data;
}
}
$aa = new talker();
$d = &$aa->get();
$aa->out(); // Hi
$d = 'How';
$aa->out(); // How
$d = 'Are';
$aa->out(); // Are
$d = 'You';
$aa->out(); // You
// final output: HiHowAreYouThese examples demonstrate how PHP references can be used to share and manipulate data across variables, function parameters, return values, and object properties.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.