<?php
function &getInstance() {
static $instance = null;
if ($instance === null) {
$instance = new stdClass();
}
return $instance;
}
$a = &getInstance(); // $a 是 $instance 的引用
$b = &getInstance(); // $b 也是同一引用
var_dump($a === $b); // true
关键点:函数声明与调用处都要加 &,才能真正返回引用而非拷贝。
<?php
class A {} class B {}
function ®istry($name) {
static $instances = array(); // 静态局部数组,跨调用保持
if (!isset($instances[$name])) {
$instances[$name] = new $name(); // 实例化并存入
}
return $instances[$name]; // 返回引用
}
$a = ®istry('A');
$b = ®istry('B');
$a2 = ®istry('A');
$b2 = ®istry('B');
echo $a === $a2 ? 'A 是同一实例' : 'A 不同';
echo $b === $b2 ? 'B 是同一实例' : 'B 不同';
// 输出:A 是同一实例 B 是同一实例
spl_autoload_register 实现延迟加载。class Service {
private static $instances = array();
private function __construct() {}
public static function get($name) {
if (!isset(self::$instances[$name])) {
self::$instances[$name] = new self();
}
return self::$instances[$name];
}
}
静态成员更符合 OOP 封装,且支持继承覆盖,推荐新代码使用。