PHP Return by Reference

PHPServer Side ProgrammingProgramming

Introduction

In PHP a function can also be made to return a reference. This is useful  to find to which variable a reference should be bound. To define a function which returns reference, prefix its name by & sign.

Example

In following example, myfunction() is defined to return by reference. It contains a static variable whose reference is returned and assigned to a global variable. Value of local static variable will also change its reference ouside is assigned with different value.

Example

 Live Demo

<?php
function &myfunction(){
   static $x=10;
   echo "x Inside function: ",$x,"\n";
   return $x;
}
$a=&myfunction(); //contains reference to 4x in function
echo "returned by reference: ", $a, "\n";
$a=$a+10; //increments variable inside function too
$a=&myfunction();
?>

Output

This example gives following output

x Inside function: 10
returned by reference: 10
x Inside function: 20

method returning reference

A class can also have a method that is able to return reference. This enables chenging value of private instance variable from outside the class

Example

 Live Demo

<?php
class myclass{
   private $val;
   function __construct($x){
      $this->val=$x;
   }
   function &getbyref(){
      return $this->val;
   }
   function getbyval(){
      return $this->val;
   }
}
$a=new myclass(10);
$b=&$a->getbyref();
$b=100;
echo "Value of private property: ", $a->getbyval();
?>

Output

Result of above script is as follows

Value of private property: 100
raja
Published on 18-Sep-2020 12:16:07
Advertisements