首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

沈逸 PHP 魔鬼特訓筆記(二):懶人函數、自定義函數與 PHP 7 新特性實戰

     編輯:PHP 相關知識

一、三大「懶人函數」深度解析

1. file_put_contents — 一行代碼完成寫檔

int file_put_contents(string $filename, mixed $data [, int $flags = 0 [, resource $context ]])
  • 等同 fopen() → fwrite() → fclose() 三步合一。
  • $data 支援字串、陣列(自動 join('', $arr))、資源流。
  • 常用旗標:FILE_APPEND 追加寫入、LOCK_EX 獨佔鎖定。

範例:

$file = 'people.txt';
$current = file_get_contents($file);
$current .= "John Smith\n";
file_put_contents($file, $current); // 覆蓋寫入
file_put_contents($file, "New Line\n", FILE_APPEND); // 追加

2. getcwd — 取得當前工作目錄

string getcwd(void)
  • 回傳腳本執行時的工作目錄(非腳本所在目錄)。
  • CLI 模式下為終端當前路徑;Web 模式下通常為網站根目錄。
  • 失敗回傳 false,某些 Unix 系統若父目錄不可讀也會失敗。
// 終端測試
php -r "echo getcwd();"
// 輸出:/home/tiger

3. substr — 靈活截取子字串

string substr(string $string, int $start [, int $length ])
參數行為範例結果
start ≥ 0從左數第 start 個字元開始(0 起算)substr('abcdef', 2)cdef
start < 0從右數第 |start| 個字元開始substr('abcdef', -2)ef
length > 0最多取 length 個字元substr('abcdef', 0, -1)abcde
length < 0結尾捨棄 |length| 個字元substr('abcdef', -3, -1)de

二、自定義函數規範與 PHP 7 型別宣告

// 傳統寫法
function genConfig() {
    return file_put_contents(getcwd().'/god.json','{}').' of bytes is written.'.PHP_EOL.'god config is created';
}

// PHP 7+ 型別宣告:回傳值型別
function genConfig(): string {
    return file_put_contents(getcwd().'/god.json','{}').' of bytes is written.'.PHP_EOL.'god config is created';
}

支援的型別:int、float、string、bool、array、callable、self、parent、類/介面名。嚴格模式需在檔案頂部宣告 declare(strict_types=1);。

三、實戰專案結構:GOD 指令列工具

目錄架構

project/
├── god                 # 入口腳本
├── god_func.php        # PHP 5 相容函數庫
└── god_func7.php       # PHP 7 型別宣告版函數庫

入口腳本 god

#!/usr/local/php/bin/php
= 2) {
    if ('-v' === $argv[1]) {
        $result = 'god version is 1.0';
    } elseif ('init' === $argv[1]) {
        $result = genConfig();
    }
}
echo $result . PHP_EOL;

god_func.php(PHP 5 版)



god_func7.php(PHP 7 版)



四、執行驗證

$ php god -v
god version is 1.0

$ php god init
18 of bytes is written.
god config is created

$ cat god.json
{}

五、最佳實踐提醒

  1. 版本相容策略:透過 PHP_VERSION 動態載入,避免維護雙版本入口。
  2. CLI 專用 Shebang:首行 #!/usr/local/php/bin/php 讓腳本可直接執行 ./god init。
  3. 錯誤處理:生產環境應加入 try-catch 捕獲寫入失敗、目錄權限不足等異常。
  4. 嚴格模式:新專案建議啟用 declare(strict_types=1); 避免隱性型別轉換 Bug。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved