Understanding Function References in PHP with Practical Examples

This article explains how PHP function references work, demonstrates their behavior with static variables and return‑by‑reference, and provides additional class‑based examples to illustrate how modifying a referenced variable affects the original data.

php Courses
php Courses
php Courses
Understanding Function References in PHP with Practical Examples

PHP function references behave similarly to variable references, allowing a function to return a reference to a variable rather than a copy of its value. The article begins with a simple function that uses a static variable $b to count calls and returns a reference to it.

<?php
function &test() {
    static $b = 0; // declare a static variable
    $b = $b + 1;
    echo $b;
    return $b;
}
$a = test(); // outputs 1
$a = 5;
$a = test(); // outputs 2
$a = &test(); // outputs 3
$a = 5;
$a = test(); // outputs 6
?>

Calling the function normally ( $a = test()) assigns the returned value to $a without creating a reference, so changes to $a do not affect $b. Using the reference operator ( $a = &test()) makes $a point to the same memory location as $b, so any modification of $a also changes $b.

$a = &test();
$a = 5;

After the assignment, the static variable $b becomes 5, demonstrating that the reference links the two variables.

The article also includes an official PHP example that shows how reference returns are commonly used with objects. A class talker contains a private property $data and a method &get() that returns a reference to this property.

//This is the way how we use pointer to access variable inside the class.
<?php
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();
$d = 'How';
$aa->out();
$d = 'Are';
$aa->out();
$d = 'You';
$aa->out();
?>
//the output is "HiHowAreYou"

Each time the variable $d (which references $aa->data) is changed, the output of out() reflects the new value, confirming that the method returns a true reference to the internal property.

By studying these examples, readers can grasp how PHP function references work, when to use them, and how they interact with static variables and object properties.

backend developmentprogrammingfunction referencereturn by referencestatic-variable
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.