views:

457

answers:

4

I'm trying to write a function that will return a reference to a PDO object. The reason for wanting a reference is if, for some reason, the PDO object gets called twice in one page load, it will just return the same object rather than initializing a new one. This isn't silly, is it? :/

function &getPDO()
{
   var $pdo;

   if (!$pdo)
   {
      $pdo = new PDO...

      return $pdo;
   }
   else
   {
      return &pdo;
   }
}

Something like that

A: 

To make a reference to a variable $foo, do this:

$bar =& $foo;

Then return $bar.

avpx
+3  A: 

Use static $pdo;.

function getPDO()
{
   static $pdo;

   if (!$pdo)
   {
      $pdo = new PDO...
   }

   return $pdo;

}
Daniel A. White
Thanks to you and all you other guys below this comment for the help. So that function will return a reference to the variable without the need for the ampersand?
Metrico
+2  A: 

Objects are always passed by reference in PHP. For example:

class Foo {
  public $bar;
}

$foo = new Foo;
$foo->bar = 3;
myfunc($foo);
echo $foo->bar; // 7

function myfunc(Foo $foo) {
  $foo->bar = 7;
}

It's only non-objects (scalars, arrays) that are passed by value. See References Explained.

In relation to your function, you need to make the variable static. var is deprecated in PHP 5. So:

function getFoo() {
  static $foo;
  if (!$foo) {
    $foo = new Foo;
  }
  return $foo;
}

No ampersand required.

See Objects and references as well.

cletus
A: 

You would write it like this

function getPDO()
{
   static $pdo;

   if (!$pdo) {
      $pdo = new PDO...
   }

   return $pdo;
}
too much php