function &test() 表示該函數返回引用而非返回值。調用時必須使用 $a =& test() 才能獲得引用綁定。
<?php
function &test() {
static $b = 0;
$b = $b + 1;
echo $b . '<br/>';
return $b;
}
$a = test(); // 輸出 1,普通調用,返回值賦值
$a = 5;
$a = test(); // 輸出 2,$b 未受 $a=5 影響
$a =& test(); // 輸出 3,引用返回,$a 與 $b 綁定同一內存地址
$a = 5;
$a = test(); // 輸出 6!$b 被修改為 5,下次遞增為 6
?>
| 調用方式 | 行為 | 影響靜態變量 |
|---|---|---|
$a = test() | 值傳遞,複製返回值 | 否 |
$a =& test() | 引用綁定,共享內存地址 | 是 |
class QueryBuilder {
private $sql = '';
public function &select($fields) {
$this->sql .= "SELECT $fields";
return $this; // 返回 $this 引用
}
public function &where($condition) {
$this->sql .= " WHERE $condition";
return $this;
}
}
$qb = new QueryBuilder();
$qb->select('*')->where('id=1'); // 鏈式調用
function &getLargeConfig() {
static $config = null;
if ($config === null) {
$config = loadHugeConfigArray(); // 僅加載一次
}
return $config; // 返回引用,避免數組複製
}
$cfg =& getLargeConfig();
$cfg['cache'] = true; // 直接修改原始配置
return $a + $b)& 不能用於 void 函數或構造函數誤區:以為 $a = test() 也能獲得引用。
事實:PHP 規定必須雙方都有 &(函數定義與調用處)才建立引用綁定。