0

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.

chaosaffe
  • 848
  • 9
  • 22

2 Answers2

2

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)
Jim Garrison
  • 85,615
  • 20
  • 155
  • 190
  • Figured that out after I asked... For future reference http://php.net/manual/en/language.oop5.references.php#95522 is a good guide, though it does not show an example using a function sadly – chaosaffe Feb 05 '15 at 03:50
0

You're returning true, not $v.

ceejayoz
  • 176,543
  • 40
  • 303
  • 368