Search code examples
phparraysoopvariablesreference

How do I assign a variable to an object, not a reference to it?


$a = some object;
$b = another object;
function do_some_stuff() {
    $c = $a;
    $b->a_property = $c;
}
do_some_stuff();
echo $b->a_property; # Undefined, becuase $c was deleted when the function exited.

When I type $b->a_property = $c, I want the PHP interpereter to do $b->a_property = $a. How do I do that, if I'm unable to assign it to $a directly?

My actual code is:

function setup() {
    $playerHeroes = [];
    $enemyHeroes = [];
    foreach ($entities as $object) {
        if ($object->team == "player") {
            $playerHeroes[] = $object;
        }
        else if ($object->team == "enemy") {
            $enemyHeroes[] = $object;
        }
    }

    foreach ($playerHeroes as $object) {
        $object->target = $enemyHeroes[array_rand($enemyHeroes)];
    }
    foreach ($enemyHeroes as $object) {
        $object->target = $playerHeroes[array_rand($playerHeroes)];
    }
}

I sort through a list of entities in the game as either being on the player's team or being on the enemy's team. Each hero must target a hero on the opposing team. When the setup function exits, $object, $playerHeroes and $enemyHeroes get destroyed. The ->target properties are accessed later, and it's null. How do I make it so that when I assign a variable to a reference of an object, it assigns it to the object itself?

EDIT: I want the variable to change when the object changes, so cloning/copying by value is not an option.

 


Solution

  • In addition to echoing the comments from @IvoP and @mega6382, it's worth noting that the problem you're having is not a "solvable" one per se. That's because what you're running into is fundamental to how objects work in PHP. You can learn all about it at http://ca2.php.net/manual/en/language.oop5.references.php.

    One of the key-points of PHP 5 OOP that is often mentioned is that "objects are passed by references by default". This is not completely true. This section rectifies that general thought using some examples.

    A PHP reference is an alias, which allows two different variables to write to the same value. As of PHP 5, an object variable doesn't contain the object itself as value anymore. It only contains an object identifier which allows object accessors to find the actual object. When an object is sent by argument, returned or assigned to another variable, the different variables are not aliases: they hold a copy of the identifier, which points to the same object. (hat tip to @tomzx)

    You'll likely do better to rearchitect your code to deal with this or use a language whose default behavior is call-by-value like C or Java.