PHP 5.6 於 2014 年釋出,雖已結束官方支援,但其引入的特性奠定了現代 PHP (7.x/8.x) 的語法基石。理解 5.6 新特性有助於維護舊專案、閱讀開源代碼、掌握語言演進脈絡。本文系統整理 10 大核心特性並附實戰範例。
允許在 const、屬性預設值、函式參數預設值中使用標量運算式(數值、字串、常量運算),不再限於字面值。
<?php
const ONE = 1;
const TWO = ONE * 2; // 2
const THREE = TWO + 1; // 3
const SENTENCE = 'Value: ' . THREE; // 'Value: 3'
class Config {
const BASE = '/var/www';
const PUBLIC = self::BASE . '/public';
const MAX_SIZE = 10 * 1024 * 1024; // 10MB
public function __construct(
public string $path = self::PUBLIC,
public int $limit = self::MAX_SIZE
) {}
}
?>
...$args取代 func_get_args(),提供型別提示、命名參數相容、效能更佳。
<?php
function logMessage(string $level, string $message, string ...$context): void {
$ctx = $context ? ' [' . implode(', ', $context) . ']' : '';
error_log("[$level] $message$ctx");
}
logMessage('INFO', 'User login', 'ip:192.168.1.1', 'ua:Chrome');
logMessage('ERROR', 'DB connection failed'); // 無 context 也合法
?>
... 參數必須是最後一個參數。int ...$ids。...$array(Splat Operator)呼叫函式時將陣列/可迭代物件展開為參數列表。
<?php
function add(int $a, int $b, int $c): int {
return $a + $b + $c;
}
$nums = [10, 20, 30];
echo add(...$nums); // 60
// 合併陣列(PHP 7.4+ 建議用 [...$a, ...$b])
$merged = [...[1,2], ...[3,4]]; // [1,2,3,4]
// 解包 Generator
function gen() { yield 1; yield 2; yield 3; }
echo add(...gen()); // 6
?>
命名空間不再僅限類別匯入,函式與常量也能 use。
<?php
namespace App\Utilities;
const DEFAULT_TZ = 'Asia/Taipei';
function formatDate(DateTimeInterface $dt): string {
return $dt->format('Y-m-d H:i:s');
}
// 另一檔案
namespace App\Controllers;
use const App\Utilities\DEFAULT_TZ;
use function App\Utilities\formatDate;
echo DEFAULT_TZ; // Asia/Taipei
echo formatDate(new DateTime()); // 2024-06-15 14:30:00
?>
use function App\Utilities\formatDate as fmtDate;
use const App\Utilities\DEFAULT_TZ as TZ;
phpdbg -qrr script.php 或 phpdbg -e script.php 進入互動模式。break, run, step, next, print, backtrace, info。PHP 5.6 前 php://input 只能讀一次,現在支援多次 fopen('php://input', 'r') 讀取,大幅降低大型 POST 資料處理的記憶體峰值。
<?php
// 可多次讀取同一請求主體
$input1 = file_get_contents('php://input');
$input2 = file_get_contents('php://input');
var_dump($input1 === $input2); // true
?>
upload_max_filesize, post_max_size, memory_limit, max_execution_time 設定。client_max_body_size / LimitRequestBody。GMP 資源升級為物件,支援標準算術運算子,可讀性大幅提升。
<?php
$a = gmp_init('12345678901234567890');
$b = gmp_init('98765432109876543210');
// 舊寫法
$sum = gmp_add($a, $b);
// 新寫法(PHP 5.6+)
$sum = $a + $b;
$diff = $a - $b;
$prod = $a * $b;
$quot = $a / $b;
$mod = $a % $b;
// 型別轉換
echo (int)$a; // 整數 (可能溢位)
echo (float)$a; // 浮點數
echo (string)$a; // 字串表示
?>
新增 gost-crypto (RFC 4357 §11.2),使用 CryptoPro S-box,取代舊 gost (S-box 不同)。
<?php
$data = 'sensitive data';
$hash = hash('gost-crypto', $data);
echo $hash; // 64 字元十六進位
?>
<?php
// 取得憑證指紋
$cert = file_get_contents('server.crt');
$fingerprint = openssl_x509_fingerprint($cert, 'sha256'); // PHP 5.6+
// Stream context 驗證對端指紋
$ctx = stream_context_create([
'ssl' => [
'peer_fingerprint' => $fingerprint, // 必須匹配
'capture_peer_cert' => true, // 取得對端憑證
'crypto_method' => STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT, // 指定 TLS 1.2
'verify_peer' => true,
'verify_peer_name' => true,
]
]);
$stream = stream_socket_client(
'ssl://api.example.com:443',
$errno, $errstr, 30, STREAM_CLIENT_CONNECT, $ctx
);
?>
default_charset 從空值改為 UTF-8,影響 htmlentities(), htmlspecialchars() 預設編碼。asp_tags:<% %> 標籤被移除。__debugInfo() 魔術方法:控制 var_dump() 輸出內容。const ARR = [1,2,3]; (PHP 5.6+)。use 支援群組導入 use A\{B, C, D}; (PHP 7.0+ 但概念源自 5.6 討論)。PHP 5.6 是「現代 PHP」的分水嶺:... 運算子、use function/const、常量運算式、phpdbg、php://input 重讀、GMP 物件化,皆為後續 7.x/8.x 大版本鋪路。維護 5.6 專案時善用這些特性;升級新版時則可無縫銜接。