str_ 字串、bool_ 布林、open_ 共用、app_ 業務、temp_ 暫時。@param, @return, @throws 完整註解。<?php
/**
* 多位元組安全截取字串
* @param string $str 輸入字串
* @param int $width 截取長度(位元組)
* @param string $suffix 省略尾碼
* @return string
*/
function fun_cutstr($str, $width = 0, $suffix = '...') {
// 1. 異常輸入早期返回
if (empty($str) || empty($width)) return $str;
// 2. 參數過濾
$width = (int)$width;
// 3. 不污染原始參數
$result = mb_strcut($str, 0, $width, 'utf-8');
// 4. mb_* 函數可能不存在,防禦性判斷
if ($result !== false && $result !== '') {
return $result . $suffix;
}
return $str;
}
// 測試
echo fun_cutstr('aaaaaaaaaaaaaaaaaaaaaaaa', 5); // aaaaa...
echo fun_cutstr('我是個技術工作者', 8); // 我是... (UTF-8 每中文字 3-4 位元組)
echo fun_cutstr(false); // false (原樣返回)
echo fun_cutstr('test', 'abc'); // test (參數過濾後 width=0)
echo fun_cutstr('', 'abc'); // '' (空字串)
?>
<?php
function &fun_cutstr($str, $width = 0) {
// 回傳參考
static $cache = '';
$cache = fun_cutstr($str, $width);
return $cache;
}
$b = &fun_cutstr('aaaaaaaaaaaa', 5); // $b 綁定函數靜態快取
fun_cutstr('cccccccccccc', 5); // 修改快取內容
echo $b; // 輸出 ccccc... (參考指向同一記憶體)
?>
警告:此模式在 PHP 5.3+ 產生 E_DEPRECATED,7.0+ 致命錯誤。現代寫法請回傳值,由呼叫端決定是否賦值給變數。
<?php
function fun_static() {
static $count = 1; // 只在第一次呼叫初始化
echo $count++ . '<br>';
}
fun_static(); // 1
fun_static(); // 2
fun_static(); // 3
?>
static 變數生命週期 = 腳本執行期間,但作用域僅限函數內。<?php
function sum() {
$args = func_get_args();
return array_sum($args);
}
echo sum(1,2,3,4,5); // 15
?>
<?php
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1,2,3,4,5); // 15
// 解包陣列呼叫
$arr = [10, 20, 30];
echo sum(...$arr); // 60
?>
<?php
declare(strict_types=1); // 檔案最頂端宣告
function add(int $a, int $b): int {
return $a + $b;
}
echo add(1, 2); // 3
echo add(1.5, 2.5); // TypeError: Argument must be int
?>