Daniel Marschall
Daniel Marschall

Reputation: 3879

PHP: What does &$this mean?

As I was revieweing PHP sources to find the deprecated call-time-references, I found following 2 things in 3rd party code:

#1
$x = array(&$this, $a, $b);

#2
&$this->foo();

I know that & is meant for marking references. But it makes no sense to me.

In re. #1: When I use array($this) , won't there be a reference saved in the array, too?

In re. #2: When I call foo() of my own instance, why do I need to use $this as reference?

Upvotes: 2

Views: 287

Answers (4)

Nikas
Nikas

Reputation: 247

You can pass value to function either by pass by value or pass by reference.in passby vaue new copy of varaible is created in memory where as in refrence just memory address is copied.in php & refers to pass by reference.

Upvotes: 1

Ruslan Bes
Ruslan Bes

Reputation: 2735

I suppose the code came from PHP4 time.

re #1 - In PHP 4 using array($this) means the same as array(clone($this)) in PHP 5. that is you get a copy of an object instead. In most cases you would like to get the same object though, not its copy. So I suppose the original author used array(&$this) exactly for that reason.

re #2 is explained in Returning References chapter of the manual

in this case it it doesn't matter if it's &$this or some &$obj. The reference in fact is applied to the value returned from foo(). This might make sense for example if foo() has some big static $cache object inside and returns part of it back. E.g.

class MyClass {
  function &foo($id){
    static $cache;
    if (!isset($cache[$id])) {
      $cache[$id] = extract_some_object_from_database($id);
    }
    return $cache[$id];
  }
}

Notice the "&foo"

Upvotes: 3

Robert
Robert

Reputation: 20286

As @cs1193 is passing current object by reference. But now it has no sense because by default objects are passed by reference. So you create reference to reference.

$x = array(&$this, $a, $b); // this would be passing reference to reference on current object.

&$this->foo(); //makes pretty no sense. $this is already reference to current object. 

In second example you need to call to method via $this because PHP don't know if you want to call class method or a function.

Upvotes: 1

cs1193
cs1193

Reputation: 1109

It is actually a workaround for pass by reference in PHP

We have reference for the usage in PHP manual http://php.net/manual/en/language.references.pass.php

Upvotes: 1

Related Questions