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; }
精彩评论