Returning a reference to an object in PHP

Asked
Active3 hr before
Viewed126 times

9 Answers

referencereturningobject
90%

Note: If you try to return a reference from a function with the syntax: return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else. , Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so. To return references, use this syntax: ,Note: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue. ,Note: Note that array_push(&collector(), 'foo'); will not work, it results in a fatal error.

<
? phpclass foo {
   public $value = 42;
   public
   function & getValue() {
      return $this - > value;
   }
}
$obj = new foo;
$myValue = & $obj - > getValue(); // $myValue is a reference to $obj->value, which is 42.$obj->value = 2;echo $myValue;                // prints the new value of $obj->value, i.e. 2.?>
load more v
88%

The example you posted is probably from PHP4 or earlier. It's no longer necessary to return objects by reference as they are almost always done that way automatically in PHP5+.,only consider using references if you are dealing with large array or similar non-object data structures,only allow a function to pass by reference if the value is maintained in a static property or attribute on the object (ie. it's not temporary variable inside the function),It's easier to think of it as "PHP allowing you to reference the return value" rather then PHP returning by reference. As mentioned above you simply place an & to tell PHP you want this, if you don't place it and try do to $var =& somefunction() you will get the error "Only variables should be assigned by reference."

Suppose you have this class:

class Fruit {
   private $color = "red";

   public
   function getColor() {
      return $this - > color;
   }

   public
   function & getColorByRef() {
      return $this - > color;
   }
}

Here's some code to test it:

echo "\nTEST RUN 1:\n\n";
$fruit = new Fruit;
$color = $fruit - > getColor();
echo "Fruit's color is $color\n";
$color = "green"; // does nothing, but bear with me
$color = $fruit - > getColor();
echo "Fruit's color is $color\n";

echo "\nTEST RUN 2:\n\n";
$fruit = new Fruit;
$color = & $fruit - > getColorByRef(); // also need to put & here
echo "Fruit's color is $color\n";
$color = "green"; // now this changes the actual property of $fruit
$color = $fruit - > getColor();
echo "Fruit's color is $color\n";
load more v
72%

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.,Reference assignment operator in PHP to assign a 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,How do you pass objects by reference in PHP 5?

< ? 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(); ?
>
load more v
65%

Returning by reference is useful when you want to use a function to find to which variable a reference should be bound. Do not use return-by-reference to increase performance. The engine will automatically optimize this on its own. Only return references when you have a valid technical reason to do so., Return by Reference , Return by Reference ,Return by reference is not only limited to function references. You also have the ability to implicitly call the function:

There are many different forms return by reference can take, including the following example:

function parent( & $var) {
   echo $var;
   $var = "updated";
}

function & child() {
   static $a = "test";
   return $a;
}

parent(child()); // returns "test"
parent(child()); // returns "updated"
load more v
75%

Note: Unlike parameter passing, here you have to use & in both places - to indicate that you want to return by reference, not a copy, and to indicate that reference binding, rather than usual assignment, should be done for $myValue. , To use the returned reference, you must use reference assigment: ,Note: If you try to return a reference from a function with the syntax: return ($this->value); this will not work as you are attempting to return the result of an expression, and not a variable, by reference. You can only return variables by reference from a function - nothing else. Since PHP 4.4.0 in the PHP 4 branch, and PHP 5.1.0 in the PHP 5 branch, an E_NOTICE error is issued if the code tries to return a dynamic expression or a result of the new operator. ,Other versions of this page PHP 4PHP 5PHP 7 (php.net)PHP 8 (php.net)

<
? phpclass foo {
   public $value = 42;
   public
   function & getValue() {
      return $this - > value;
   }
}
$obj = new foo;
$myValue = & $obj - > getValue(); // $myValue is a reference to $obj->value, which is 42.$obj->value = 2;echo $myValue;                // prints the new value of $obj->value, i.e. 2.?>
load more v
40%

PHP memory references are stored in a key-value store called the symbols table.,In PHP, references are “aliases” that allow two different variables to read and write a single value.,PHP maintains a count of references towards an object from the time it is created. When there are no references to that object in the symbols table, the PHP garbage collector removes it.,If you’re interested in reading more about PHP performance features, check out this post by fellow Toptaler Vilson Duka.

In PHP, references are “aliases” that allow two different variables to read and write a single value. Put another way, they are mechanisms that allow access to the same value from variables with different names so that they behave as if they are the same variable. Keep in mind that in PHP, variable names and the content of variables are two entirely different things, linked in what it is called the “symbols table.” So, when we create a reference, it simply adds an alias for that variable in the symbol table. Suppose we have the following code:

$a = new Foo();
load more v
22%

Though the main reason for using const reference is efficiency, there are restrictions on when this choice could be used. If a function returns an object that is passed to it, either by object invocation or as a method argument, we can increase the efficiency of the method by having it pass a reference.,The function could return,If a method or function returns a local object, it should return an object, not a reference.,A constant reference to an object

For example, suppose we want to write a function Maximum() that returns the larger of two Complx objects, where the Complx is defined as below.

#include <iostream>
#include <cmath>

using namespace std;

class Complx {
private:
	double real;
	double imag;
public:
	Complx() {}
	Complx(double r, double i): real(r), imag(i) {}
	Complx  operator+(const Complx & c) const {
		return Complx(real + c.real, imag + c.imag);
	}
	Complx & operator=(const Complx &c;) {
		real = c.real;
		imag = c.imag;
		return *this;
	}

	friend ostream& operator<<(ostream &os;, const Complx &c;);
	double size() const {
		return sqrt(real*real + imag*imag);
	}
};

ostream & operator<<(ostream &os;, const Complx & c) {
	os << "(" << c.real << "," << c.imag << ")";
	return os;
}

/*
Complx Maximum(const Complx &c1;, const Complx &c2;) {
	
	if (c1.size() > c2.size()) 
		return c1;
	else
		return c2;
}
*/

const Complx & Maximum(const Complx &c1;, const Complx &c2;) {
	
	if (c1.size() > c2.size()) 
		return c1;
	else
		return c2;
}

int main( ) 
{ 
	Complx c1(10,30);
	Complx c2(13,25);
	Complx mx = Maximum (c1,c2);

	cout << " c1 = " << c1 << endl;
	cout << " c2 = " << c2 << endl;
	cout << "Maximum(c1,c2) = " << mx << endl;

	Complx c3 (20,40);
	Complx c4,c5;
	c5 = c4 = c3;

	cout << c4 << " got its value from c3" << endl;

	Complx c6 = c1 + c2;
	cout << " c6 (c1+c2) = " << c6 << endl;

	Complx c7;
	c1 + c2 = c7;
	return 0; 
}
load more v
60%

Unlike other types of variable, whenever you assign, pass, or return an object, you’re passing a reference to the object, not a copy. This is usually what you want to happen, since the function or method you pass an object to usually needs to work on the actual object, not a copy of it. For example:,Now, whenever you call myFunc() and pass a variable to it, PHP passes a reference to the variable, rather than the variable’s value.,To pass an argument by reference, you place an ampersand before the parameter name when you define the function:,The ampersand before the parameter in the function definition is sufficient to pass the variable by reference.

An easy way to create a reference is known as assigning by reference. Consider the following simple example:

$myVar = "Hi there";
$anotherVar = $myVar;
$anotherVar = "See you later";
echo $myVar; // Displays "Hi there"
echo $anotherVar; // Displays "See you later"

Now, let’s change the above example to assign $myVar to $anotherVar by reference, rather than by value. To do this, we simply put an ampersand (&) after the equals sign:

$myVar = "Hi there";
$anotherVar = & $myVar;
$anotherVar = "See you later";
echo $myVar; // Displays "See you later"
echo $anotherVar; // Displays "See you later"

When you unset a reference, you’re merely removing that reference, not the value that it references:

$myVar = "Hi there";
$anotherVar = & $myVar;
$anotherVar = "See you later";
unset($anotherVar);
echo $myVar; // Displays "See you later"

The value remains in memory until you unset all references to it, including the original variable:

$myVar = "Hi there";
$anotherVar = & $myVar;
$anotherVar = "See you later";
unset($anotherVar);
unset($myVar);
echo $myVar; // Displays ""

To pass an argument by reference, you place an ampersand before the parameter name when you define the function:

function myFunc( & $myParam) {
   // Do something with $myParam
}

Let’s look at a simple example of passing by reference:

function goodbye( & $greeting) {
   $greeting = "See you later";
}

$myVar = "Hi there";
goodbye($myVar);
echo $myVar; // Displays "See you later"

By the way, don’t be tempted to put an ampersand before the argument name in your function call:

goodbye( & $myVar); // Don't do this!

As well as passing references to functions, you can return references from functions. To do this, place an ampersand before the function name when you define the function. You should also use assign-by-reference (=&) when assigning the returned reference to a variable, otherwise you’ll merely assign the value, not the reference. Here’s an example:

$numWidgets = 10;

function &getNumWidgets() {
  global $numWidgets;
  return $numWidgets;
}

$numWidgetsRef =& getNumWidgets();
$numWidgetsRef--;
echo "$numWidgets = $numWidgets<br>";  // Displays "9"
echo "$numWidgetsRef = $numWidgetsRef<br>";  // Displays "9"

Another handy use of references is to change values in an array when using a foreach loop. With a regular foreach loop, you’re working with copies of the array values, so if you change a value you’re not affecting the original array. For example, let’s try to change an array of band names to uppercase with a foreach loop:

$bands = array( "The Who", "The Beatles", "The Rolling Stones" );

foreach ( $bands as $band ) {
  $band = strtoupper( $band );
}

echo "<pre>";
print_r( $bands );
echo "</pre>";

The above example displays:

Array
   (
      [0] => The Who[1] => The Beatles[2] => The Rolling Stones
   )

As you can see, the original array has not been changed by the foreach loop. However, if we place an ampersand before $band in the foreach statement then $band becomes a reference to the original array element, rather than a copy. We can then convert the array elements to uppercase:

$bands = array( "The Who", "The Beatles", "The Rolling Stones" );

foreach ( $bands as &$band ) {
  $band = strtoupper( $band );
}

echo "<pre>";
print_r( $bands );
echo "</pre>";

Our code now runs as intended, producing this:

Array
   (
      [0] => THE WHO[1] => THE BEATLES[2] => THE ROLLING STONES
   )

When you use global to access a global variable within a function, you are in fact creating a reference to the global variable in the $GLOBALS array. So:

function myFunction() {
   global $globalVariable;
}

does the same thing as:

function myFunction() {
   $globalVariable = & $GLOBALS["globalVariable"];
}

When you use the $this keyword within an object’s method to refer to the object, then it’s worth remembering that $this is always a reference to the object, rather than a copy of it. For example:

class MyClass {

   var $aProperty = 123;

   function aMethod() {
      $this - > aProperty = 456; // $this is a reference to the object
   }
}

$myObject = new MyClass();
$myObject - > aMethod();
echo $myObject - > aProperty; // Displays "456"

Unlike other types of variable, whenever you assign, pass, or return an object, you’re passing a reference to the object, not a copy. This is usually what you want to happen, since the function or method you pass an object to usually needs to work on the actual object, not a copy of it. For example:

class MyClass {
   // (Class definition here)
}

$myObject = new MyClass();
$yourObject = $myObject; // $yourObject and $myObject point to the same object
load more v
48%

Example #3 Returning a reference from a function,Example #6 Returning an object,Example #1 Use of return,Example #2 Returning an array to get multiple values

float(3)
load more v

Other "reference-returning" queries related to "Returning a reference to an object in PHP"