萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 5.6 新特性完整指南:常量標量運算式、可變參數、解包、use function/const、phpdbg 與更多

前言

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 function / use const:函式與常量匯入

命名空間不再僅限類別匯入,函式與常量也能 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:內建互動式除錯器

  • SAPI 模組,無需 Xdebug 即可斷點、單步、檢查變數。
  • 啟動:phpdbg -qrr script.php 或 phpdbg -e script.php 進入互動模式。
  • 常用指令:break, run, step, next, print, backtrace, info。
  • 適合 CI/CD 環境無法安裝 Xdebug 時的快速除錯。

六、php://input 可重複讀取

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
?>

七、大檔案上傳支援 (> 2GB)

  • 移除 32 位元系統 2GB 上傳限制。
  • 需搭配 upload_max_filesize, post_max_size, memory_limit, max_execution_time 設定。
  • Nginx/Apache 同需調整 client_max_body_size / LimitRequestBody。

八、GMP 物件運算子多載

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 雜湊演算法

新增 gost-crypto (RFC 4357 §11.2),使用 CryptoPro S-box,取代舊 gost (S-box 不同)。

<?php
$data = 'sensitive data';
$hash = hash('gost-crypto', $data);
echo $hash; // 64 字元十六進位
?>

十、SSL/TLS 改進:證書指紋驗證與加密方法控制

<?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 專案時善用這些特性;升級新版時則可無縫銜接。

copyright © 萬盛學電腦網 all rights reserved