本文濃縮 PHP 基礎語法精華,適合有程式基礎者快速查閱、建立心智模型。
<?php phpinfo(); ?>
瀏覽此檔確認 PHP 版本、載入模組、設定參數。
<?php ... ?> // 標準、推薦
<? ... ?> // 短標籤,需啟用 short_open_tag
<script language="php">...</script> // XML 相容
<% ... %> // ASP 風格,已移除 (PHP 7+)
語句以分號 `;` 結束,PHP 標籤結束隱含語句結束。
// 單行註解 (C++)
# 單行註解 (Shell)
/* 多行註解 (C) */
/** 文件區塊註解 (PHPDoc) */
$int = 123; // 整數
$float = 1.23; // 浮點數
$str1 = '單引號'; // 字面字串
$str2 = "雙引號 $int 解析變數"; // 解析變數、跳脫序列
$bool = true; // 布林
$arr = [1, 2, 3]; // 索引陣列 (PHP 5.4+ 短語法)
$map = ['a' => 1, 'b' => 2]; // 關聯陣列
$obj = new stdClass(); // 物件
$null = null; // 空值
$res = fopen('file.txt', 'r'); // 資源型別
| 功能 | 函式 | 範例 |
|---|---|---|
| 長度 | `strlen()`, `mb_strlen()` | `mb_strlen('中文', 'UTF-8')` |
| 查找 | `strpos()`, `strrpos()`, `stripos()` | `strpos($haystack, $needle)` |
| 替換 | `str_replace()`, `str_ireplace()`, `preg_replace()` | `str_replace('a', 'b', $str)` |
| 截取 | `substr()`, `mb_substr()` | `mb_substr($str, 0, 10, 'UTF-8')` |
| 分割 | `explode()`, `str_split()`, `preg_split()` | `explode(',', $csv)` |
| 合併 | `implode()`, `join()` | `implode(',', $arr)` |
| 大小寫 | `strtolower()`, `strtoupper()`, `ucfirst()`, `ucwords()`, `mb_convert_case()` | |
| 修剪 | `trim()`, `ltrim()`, `rtrim()` | `trim($str, " \t\n\r\0\x0B")` |
| 跳脫 | `htmlspecialchars()`, `htmlentities()`, `addslashes()`, `json_encode()` | 輸出前必做 |
| 格式化 | `sprintf()`, `printf()`, `number_format()` | `sprintf('%04d', 7)` → `0007` |
$a = ['a', 'b', 'c'];
$a[] = 'd'; // 追加
unset($a[1]); // 刪除
$a = array_values($a); // 重建索引
// 關聯陣列
$map = ['name' => 'Tom', 'age' => 25];
$map['city'] = 'Taipei';
unset($map['age']);
isset($map['name']); // true
array_key_exists('name', $map); // true (含 null 值)
// 遍歷
foreach ($map as $key => $val) { ... }
// 常用函式
array_merge($a, $b);
array_map('strtoupper', $a);
array_filter($a, fn($v) => $v > 10);
array_reduce($a, fn($carry, $v) => $carry + $v, 0);
array_keys($map), array_values($map);
in_array('Tom', $map); // 搜尋值
// 替代語法 (適合模板混合 HTML)
if ($cond): ... elseif ($cond2): ... else: ... endif;
while ($row = $stmt->fetch()): ... endwhile;
foreach ($items as $item): ... endforeach;
switch ($x): case 1: ... break; default: ... endswitch;
// 完整型別宣告
function add(int $a, int $b): int { return $a + $b; }
// 箭頭函式 (自動捕獲外部變數)
$multiply = fn(int $a, int $b): int => $a * $b;
// 可變參數
function sum(int ...$nums): int { return array_sum($nums); }
// 命名參數 (PHP 8+)
function setCookie(string $name, string $value, int $expire = 0, string $path = '/', string $domain = '', bool $secure = false, bool $httponly = true) { ... }
setCookie(name: 'sid', value: 'abc123', secure: true);
| 變數 | 用途 |
|---|---|
| `$_GET` | URL 查詢字串參數 |
| `$_POST` | POST 表單資料 (application/x-www-form-urlencoded, multipart/form-data) |
| `$_REQUEST` | GET+POST+COOKIE 合併 (不建議使用,來源不明確) |
| `$_SERVER` | 伺服器與執行環境資訊 (REQUEST_METHOD, HTTP_HOST, REMOTE_ADDR...) |
| `$_ENV` | 環境變數 |
| `$_COOKIE` | HTTP Cookie |
| `$_FILES` | 上傳檔案資訊 |
| `$_SESSION` | Session 資料 (需 session_start()) |
| `$GLOBALS` | 所有全域變數參考 |
<?php
// 開發環境
error_reporting(E_ALL);
ini_set('display_errors', '1');
// 生產環境
ini_set('display_errors', '0');
ini_set('log_errors', '1');
ini_set('error_log', '/var/log/php/error.log');
// 自訂錯誤處理
set_error_handler(function ($severity, $message, $file, $line) {
if (!(error_reporting() & $severity)) return false;
throw new ErrorException($message, 0, $severity, $file, $line);
});
// 例外處理
try {
$pdo = new PDO($dsn, $user, $pass);
} catch (PDOException $e) {
error_log('DB 連線失敗: ' . $e->getMessage());
// 顯示友善錯誤頁
}
熟練掌握上述核心語法與常用函式,是 PHP 開發的基本功。建議搭配 PHP 官方中文手冊 深入研讀各函式細節,並實作小專案鞏固應用。