Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP References: An understanding

Tags:

php

reference

I have seen in my journey to creaitng and building some of my php applications, the & symbol within front of vars, = and class names.

I understand that these are PHP References, but the docs i have seen and looked at seem to just not explain it in a way that i understand or confusing. How can you explain the following examples that i have seen to make them more understandable.

  public static function &function_name(){...}

  $varname =& functioncall();

  function ($var, &$var2, $var3){...}

Much appreciated

like image 675
Simon Davies Avatar asked Feb 27 '13 17:02

Simon Davies


People also ask

What are references in PHP?

A PHP reference is an alias, which allows two different variables to write to the same value. In PHP, an object variable doesn't contain the object itself as value. It only contains an object identifier which allows object accessors to find the actual object.

How do I reference a variable in PHP?

In PHP, variable name and variable content are different, so the same content can have different names. A reference variable is created by prefixing & sign to original variable. Hence b=&a will mean that bisareferewncevariableofa.

Does PHP pass arrays by reference?

With regards to your first question, the array is passed by reference UNLESS it is modified within the method / function you're calling. If you attempt to modify the array within the method / function, a copy of it is made first, and then only the copy is modified.

What is the difference between accessing a variable by name and by reference PHP?

KEY DIFFERENCEIn Call by value, a copy of the variable is passed whereas in Call by reference, a variable itself is passed.


1 Answers

Let's say you have two functions

$a = 5;
function withReference(&$a) {
    $a++;
}
function withoutReference($a) {
    $a++;
}

withoutReference($a);
// $a is still 5, since your function had a local copy of $a
var_dump($a);
withReference($a);
// $a is now 6, you changed $a outside of function scope
var_dump($a);

So, passing argument by reference allows function to modify it outside of the function scope.

Now second example.

You have a function which returns a reference

class References {
    public $a = 5;
    public function &getA() {
        return $this->a;
    }
}

$references = new References;
// let's do regular assignment
$a = $references->getA();
$a++;
// you get 5, $a++ had no effect on $a from the class
var_dump($references->getA());

// now let's do reference assignment
$a = &$references->getA();
$a++;
// $a is the same as $reference->a, so now you will get 6
var_dump($references->getA());

// a little bit different
$references->a++;
// since $a is the same as $reference->a, you will get 7
var_dump($a);
like image 145
Marko D Avatar answered Nov 15 '22 12:11

Marko D