Search code examples
phpoopreferenceinstances

Setting variable to an instance of an object in php


Okay, I am ripping my hair out here...

I clearly am missing something simple. I am trying to prevent database hits, so I am using a simple function that checks to see if there is an instace of the object already in memory, and if it is, returns the instance, and if not, goes and gets it from the database.

private function RetrieveFromMemory($Id, $Object)
{
    $mymap=$this->ColumnMap;
    $key = $this->Key;
    foreach($this->InMemory as $v) {
        if($v->$key == $Id) {
            /*
            foreach (get_object_vars($v) as $key => $value) {
                $Object->$key = $value;
            }
            */
            $Object = $v;
            trace('Retrieved '.get_class($v).' from memory');
            return true;

        }
    }
    return false;
}

If I uncomment the foreach I can fill the properties fine, but it is a new instance. I want the same instance of the thing, but using $Object = $v; does not set $Object to the same instance as $v... It just leaves the original empty object.


Solution

  • You are attempting to change the value of the parameter $Object inside the function and expecting that change to be visible after the function completes.

    PHP passes arguments by value by default, so you either need to

    1. Change the function to return the value it found, and change how you call it; or
    2. Tell PHP to pass parameters by reference: function RetrieveFromMemory($Id, &$Object)