有些 PHP 觀念剛接觸時特別繞,理解起來頗費力。把它們系統性列出來,希望能让後來者在路上少踩幾顆釘子。
$a = 'hello';
$hello = 'hello everyone';
echo $$a; // 輸出 hello everyone
$b = 'John'; $c = 'Mary'; $e = 'Joe';
$students = array('b', 'c', 'e');
echo ${$students[1]}; // 輸出 Mary
把 hello 賦值給 $a,於是 $$a 等價於 ${hello},也就是 $hello。
但 $$students[1] 這種寫法會造成歧義,PHP 解析器可能無法正確理解——雖然 [ 的運算子優先序較高,結果卻未必能輸出。正確寫法是 ${$students[1]}。
$numbers = array(1, 2, 3, 4, 5, 6); $a = array_shift($numbers); // 取出頭部元素,索引重排 $b = array_unshift($numbers, 'first'); // 在頭部插入,回傳新長度 $c = array_pop($numbers); // 取出尾端元素 $d = array_push($numbers, 'last'); // 在尾端追加,回傳新長度
建立 Unix 時間戳(1970/1/1 至今的秒數)有三種方式:
time(); // 目前時間戳
mktime(6, 30, 0, 5, 22, 2012); // 指定時分秒月日年的時間戳
strtotime("+1 day"); // 相對時間,如 'last Monday'
checkdate($month, $day, $year) 用來驗證日期是否合法,例如 checkdate(5, 32, 2012) 會回傳 false。
拿到時間戳後需要格式化為可讀形式,有 date($format, $timestamp) 與 strftime($format, $timestamp) 兩種。較推薦後者:strftime("%Y-%m-%d %H:%M:%S")。
$_SERVER 提供了大量請求與環境線索,常用的有:
$_SERVER['SERVER_NAME'] // 主機名稱 $_SERVER['SERVER_ADDR'] // 伺服器 IP $_SERVER['SERVER_PORT'] // 埠號 $_SERVER['DOCUMENT_ROOT'] // 文件根目錄 $_SERVER['REMOTE_ADDR'] // 客戶端 IP $_SERVER['REQUEST_URI'] // 請求路徑 $_SERVER['QUERY_STRING'] // 查詢字串 $_SERVER['REQUEST_METHOD'] // GET / POST $_SERVER['HTTP_USER_AGENT']// 使用者代理
function test() {
$a = 0;
echo $a;
$a++;
}
test(); test(); test(); // 每次都輸出 0
普通區域變數在函式返回後即消失,$a++ 的結果不會被保留。
function test1() {
static $a = 0;
echo $a;
$a++;
}
test1(); test1(); test1(); // 依序輸出 0 1 2
加上 static 後,變數仍只存在於該函式的作用域內,但離開作用域時數值不會丟失,因此第二次呼叫時 $a 已是 1。
至於全球變數,PHP 要求在函式內顯式宣告才能使用:
$a = 1; $b = 2;
function Sum() {
global $a, $b;
$b = $a + $b;
}
function Sum1() {
$GLOBALS['b'] = $GLOBALS['a'] + $GLOBALS['b'];
}
$a = 'arist'; $b = $a; // 複製 $b = 'ming'; echo $a; // arist $a = 'arist'; $b = &$a; // 參照 $b = 'ming'; echo $a; // ming
可以這樣理解:媽媽叫你「明明」,主管叫你「小言」,但不論哪個稱呼,指的都是同一個人。& 就是讓不同名字指向同一個記憶體位置的手段,因此改動 $b 也就改動了 $a。
function ref_test(&$var) {
return $var *= 2;
}
$a = 10;
ref_test($a);
echo $a; // 20
參數前加 &,傳入的不是副本而是真正的值,函式內的修改會直接反映到外部。
function &increment() {
static $var = 0;
$var++;
return $var;
}
$a = & increment(); // 1
increment(); // 2
$a++; // 3
increment(); // 4
echo "a: {$a}";
把 increment() 視為一個變數即可理解:$a 與函式回傳的那個靜態變數指向同一份值,改動任何一方都會同步。
class Trones {
static public $fire = "I am fire.";
public $water = "I am water";
static function getFire() {
return $this->fire; // 錯:靜態方法中沒有 $this
}
static function Fire() {
return self::$fire; // 對:用 self 存取靜態屬性
}
}
echo Trones::Fire();
官方定義說得很清楚:宣告為 static 的屬性或方法,不需要建立實例即可存取;而靜態屬性無法透過實例的物件運算子 -> 存取(靜態方法則可以)。$this 是個偽變數,代表某個實例,在沒有實例的靜態上下文中自然不存在。
反過來,也不能用 :: 去存取普通屬性。正確的存取方式取決於你身在哪裡:類別內部用 self::(等同 Trones::),類別外部用 Trones::。繼承類別同樣適用這套規則。
class Trones {
protected $fire = " fire ";
public $water = " water ";
static private $trones = "Trones";
protected function getFire() { return $this->fire; }
static public function TheDragon() {
return __METHOD__ . " use " . $this->getFire(); // 錯:靜態方法中不能用 $this
}
static private function getTrones() { return self::$trones; }
}
class Kings extends Trones {
static function TheSevenKing() {
return __METHOD__ . "gets the " . self::getTrones(); // 錯:私有成員無法被子類存取
}
}
兩個錯誤各自對應一條規則。第一,靜態方法中不能使用任何物件運算子,把 $this->getFire() 拿掉即可。第二,private 成員連子類別都無法存取,只有 protected 與 public 才能跨過繼承界線。
至于 Interface、Implement、abstract 這些機制,如果你不打算打造大型框架或網站,暫時不碰也無妨——真正需要它們時,你自然會明白它們存在的理由。