<?php
// 簡單函數:接收參數、返回值
function fontBold(string $content): string
{
return "<b>{$content}</b>";
}
$str = "簡單的函數測試!";
echo "普通文本:{$str}<br>";
echo "加粗文本:" . fontBold($str) . "<br>";
<?php
function fontColor(string $content, string $color = 'blue'): string
{
return "<font color=\"{$color}\">{$content}</font>";
}
$str = "顏色測試";
echo $str . "<br>";
echo fontColor($str . " 這是不帶顏色參數的(默認藍色)!") . "<br>";
echo fontColor($str, "red") . " 這是帶顏色參數的(紅色)!<br>";
規則: 有默認值的參數必須放在無默認值參數之後。
<?php
/**
* 遞歸判斷是否為整數(教學示例,實際用 is_int/filter_var)
*/
function checkInt(float $num): bool
{
if ($num > 1) {
return checkInt($num - 1);
} elseif ($num < 0) {
return checkInt(($num * -1) - 1);
} else {
// 0 < num < 1 之間不是整數
return $num > 0 ? false : true; // 0 是整數
}
}
$num = 3;
echo $num . (checkInt($num) ? " 是整數!" : " 不是整數") . "<br>";
遞歸三要素: 終止條件、遞歸調用、問題規模縮小。注意: PHP 無尾調用優化,深度遞歸會棧溢出(通常 < 10000 層)。
<?php
function write(string $content): void
{
echo $content;
}
function writeBold(string $content): void
{
echo "<b>{$content}</b>";
}
// 變量存儲函數名
$func = 'write';
$func("這是動態調用不加粗的例子!"); // 等同 write(...)
$func = 'writeBold';
$func("這是動態調用加粗的例子!"); // 等同 writeBold(...)
// 實際應用:路由分發、策略模式
$handlers = [
'get' => 'handleGet',
'post' => 'handlePost',
'put' => 'handlePut',
'delete' => 'handleDelete',
];
$method = strtolower($_SERVER['REQUEST_METHOD']);
($handlers[$method] ?? 'handleNotFound')();
global 關鍵字<?php
$x = 10;
function testGlobal()
{
global $x; // 引入全局變量
$x = 20;
}
testGlobal();
echo $x; // 20
// 等價:$GLOBALS 超全局數組
function testGlobals()
{
$GLOBALS['x'] = 30;
}
testGlobals();
echo $x; // 30
<?php
function counter(): int
{
static $count = 0; // 僅初始化一次
return ++$count;
}
echo counter() . "\n"; // 1
echo counter() . "\n"; // 2
echo counter() . "\n"; // 3
// 靜態變量生命週期 = 腳本運行期間,但作用域僅限函數內
<?php
declare(strict_types=1); // 文件頂部聲明,強制嚴格類型
function add(int $a, int $b): int
{
return $a + $b;
}
add(1, 2); // 3
add(1.5, 2.8); // TypeError: Argument must be int, float given
// 嚴格模式下不發生隱式類型轉換
<?php
function sum(...$numbers): float
{
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // 10
// 陣列解包調用
$vals = [10, 20, 30];
echo sum(...$vals); // 60
<?php
$multiply = function(int $a, int $b): int {
return $a * $b;
};
echo $multiply(3, 4); // 12
// 閉包:捕獲外部變量
$factor = 10;
$scale = function(int $x) use ($factor) {
return $x * $factor;
};
echo $scale(5); // 50
// 箭頭函數(PHP 7.4+,自動捕獲值作用域)
$scaleFn = fn($x) => $x * $factor;
echo $scaleFn(5); // 50
getUser()、calculateTotal()、isValid()/** ... */ 格式,IDE 可提示global、$GLOBALS