开发者

PHP function to return a reference a variable

开发者 https://www.devze.com 2022-12-15 16:29 出处:网络
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

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 th开发者_开发技巧e 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


Use static $pdo;.

function getPDO()
{
   static $pdo;

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

   return $pdo;

}


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.


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

$bar =& $foo;

Then return $bar.


You would write it like this

function getPDO()
{
   static $pdo;

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

   return $pdo;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消