PHP 是專為 Web 開發設計的伺服器端腳本語言,語法融合 C、Java、Perl 風格,學習曲線平緩。本文系統整理核心基礎語法,作為入門速查手冊。
<?php echo '標準標籤,推薦使用'; ?>
<? echo '短標籤,需 php.ini 啟用 short_open_tag'; ?>
<script language="php"> echo 'XML 相容寫法'; </script>
最佳實踐:純 PHP 檔案**省略結束標籤** `?>`,避免輸出前多餘空白導致 Header 已送出錯誤。
snake_case(變數/函式)、PascalCase(類別)、UPPER_SNAKE(常數)| 型別 | 範例 | 說明 |
|---|---|---|
| Integer | `123`, `-10`, `0123` (八進位), `0x1A` (十六進位) | 平台相關長度,通常 64 位元 |
| Float | `1.23`, `1.2e3`, `7E-10` | 雙精度浮點數 |
| String | `'單引號'`, `"雙引號解析變數 $var"`, `<<| 雙引號支援跳脫序列 `\n`, `\t`, `\"` | |
| Boolean | `true`, `false` | 條件判斷核心 |
<?php
// 定義
$indexed = ['apple', 'banana', 'cherry']; // 索引陣列 0,1,2
$assoc = ['name' => 'Tom', 'age' => 25]; // 關聯陣列
// 存取
echo $indexed[0]; // apple
echo $assoc['name']; // Tom
// 新增/修改
$indexed[] = 'date'; // 自動索引
$assoc['city'] = 'Taipei';
// 刪除
unset($indexed[1]); // 移除 banana
$indexed = array_values($indexed); // 重建索引
// 常用函式
count($arr); // 元素個數
array_key_exists('key', $arr); // 檢查鍵存在
in_array('value', $arr); // 檢查值存在
array_merge($a, $b); // 合併陣列
array_map('strtoupper', $arr); // 映射轉換
array_filter($arr, fn($v) => $v > 10); // 過濾
<?php
class User
{
public string $name;
private int $age;
public function __construct(string $name, int $age)
{
$this->name = $name;
$this->age = $age;
}
public function greet(): string
{
return "Hello, I'm {$this->name}.";
}
}
$user = new User('Alice', 30);
echo $user->greet(); // Hello, I'm Alice.
<?php
define('APP_NAME', 'MyApp'); // 全域常數
const API_VERSION = 'v1'; // 類別常數或命名空間常數
echo APP_NAME; // MyApp
| 類別 | 運算子 | 範例 |
|---|---|---|
| 算術 | `+` `-` `*` `/` `%` `**` | `2 ** 3` = 8 (冪次) |
| 字串 | `.` (串接) | `'Hello ' . 'World'` |
| 指派 | `=` `+=` `-=` `*=` `/=` `.=` | `$a += 5` 等同 `$a = $a + 5` |
| 比較 | `==` `===` `!=` `!==` `<` `>` `<=` `>=` `<=>` (太空船) | `===` 嚴格比較型別與值 |
| 邏輯 | `&&` `||` `!` `and` `or` `xor` | `&&` 優先級高於 `and` |
| 位元 | `&` `|` `^` `~` `<<` `>>` | 位元運算 |
| 其他 | `??` (Null 合併) `?:` (Elvis) `->` (物件存取) `::` (靜態存取) | `$x = $y ?? 'default'` |
<?php
if ($score >= 90) {
echo '優等';
} elseif ($score >= 60) {
echo '及格';
} else {
echo '不及格';
}
// 三元運算子
$grade = $score >= 60 ? '及格' : '不及格';
// Null 合併 (PHP 7+)
$name = $_GET['name'] ?? '訪客';
// Match 表達式 (PHP 8+)
$message = match (true) {
$score >= 90 => '優等',
$score >= 60 => '及格',
default => '不及格',
};
<?php
// while
while ($row = $stmt->fetch()) { ... }
// do-while
do { ... } while ($cond);
// for
for ($i = 0; $i < 10; $i++) { ... }
// foreach (陣列/物件迭代)
foreach ($users as $user) { ... }
foreach ($users as $id => $user) { ... }
// 迴圈控制
break; // 跳出迴圈
continue; // 跳過本次迴圈
<?php
switch ($action) {
case 'create':
create();
break;
case 'update':
case 'edit':
update();
break;
default:
throw new InvalidArgumentException("Unknown action: $action");
}
// Match 更嚴格、回傳值、無隱性轉型
$result = match ($status) {
200, 201 => 'Success',
404 => 'Not Found',
default => 'Error',
};
<?php
// 型別宣告、回傳型別、預設值、可變參數
function sum(int ...$numbers): int
{
return array_sum($numbers);
}
echo sum(1, 2, 3); // 6
// 匿名函式 / 閉包
$multiply = fn(int $a, int $b): int => $a * $b;
echo $multiply(3, 4); // 12
// 箭頭函式自動捕獲外部變數
$factor = 10;
$scale = fn($x) => $x * $factor;
echo $scale(5); // 50
include:失敗產生 Warning 繼續執行require:失敗產生 Fatal Error 停止執行include_once / require_once:防止重複包含(類別定義必須)現代專案:使用 Composer PSR-4 自動載入,不再手寫 include/require。
掌握上述核心語法,即可閱讀、撰寫大多數 PHP 程式碼。建議接著學習:Composer 依賴管理、PSR 規範、PDO 資料庫操作、MVC 架構、單元測試,逐步建立現代 PHP 開發能力。