Question

I'm having some trouble with references in PHP. Let's say you do the following:

<?php

class foo
{
    public $str;
}

class bar
{
    public $txt;
}

class x
{
    private $objs = array();

    public function add(&$obj)
    {
        $this->objs[] = $obj;
    }

    public function update()
    {
        foreach($this->objs as $obj)
        {
            $obj = new bar();
            $obj->txt = "bar";
        }
     }
}

//Make x
$x = new x();

//Make foo
$foo = new foo();
$foo->str = "foo";

//Add
$x->add($foo);

//update
$x->update();

var_dump($foo);

The var_dump at the end gives:

class foo#2 (1) {
  public $str =>
  string(3) "foo"
}

Evidently, I'm not storing my reference properly in the array. Is there a way to do this so that $foo is of type bar after $x->update()?

Was it helpful?

Solution

Try this. I don't know why or how this works. Just added some '&'s all over the place.

public function add(&$obj)
{
    $this->objs[] = &$obj;
}

public function update()
{
    foreach($this->objs as &$obj)
    {
        $obj = new bar();
        $obj->txt = "bar";
    }
}

UPDATE

An object is actually only logically(to us) a reference, but technically different from references in php.

PHP manual explains this. Object variables are different from references. Reference is an alias to a variable. It points to the same data held by that variable. Object is a datatype that holds object identifiers. So you can also have references to objects.

$a = new foo();
$b = $a;

$a and $b here are 2 different variables both having the same value (object id), not aliases or reference types. This works just like $a = 1;$b = $a; .

Arrays can store references. By doing var_dump($x->objs); you can see the object references in array.

You don't often see references of objects in var_dump outputs because references get constantly dereferenced by assignments. You also can't do a call-time pass-by-reference to functions like var_dump and array_push.

Your problem was caused by the dereferencing and missing the additional reference operators.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top