1

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

1
  • return &$pdo; is a syntax error. You should do return $pdo;. The & sign is only used in the function declaration and not when you return it. Commented Aug 8, 2013 at 0:07

4 Answers 4

3

Use static $pdo;.

function getPDO()
{
   static $pdo;

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

   return $pdo;

}
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@dave, without the ampersand it will not return a reference. What it returns is a copy of the object identifier php.net/manual/en/language.oop5.references.php
2

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.

1 Comment

Not true, what is passed is a copy of their identifier and not a reference. The link you linked explains in the first para...
1

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

$bar =& $foo;

Then return $bar.

Comments

0

You would write it like this

function getPDO()
{
   static $pdo;

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

   return $pdo;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.