在PHP中,你可以使用函數參數來實現動態功能
function greet($name, $greeting = "Hello") {
echo "$greeting, $name!";
}
greet("John"); // 輸出 "Hello, John!"
greet("Jane", "Hi"); // 輸出 "Hi, Jane!"
function displayValue(int $value): void {
echo "The value is: $value";
}
displayValue(42); // 輸出 "The value is: 42"
function sum(...$numbers): int {
$total = 0;
foreach ($numbers as $number) {
$total += $number;
}
return $total;
}
echo sum(1, 2, 3, 4); // 輸出 "The sum is: 10"
function setOptions(array $options): void {
foreach ($options as $key => $value) {
echo "Set option $key to $value\n";
}
}
setOptions([
'color' => 'red',
'size' => 10,
]);
$greet = function ($name) {
echo "Hello, $name!";
};
$greet("John"); // 輸出 "Hello, John!"
通過這些方法,你可以根據需要實現動態功能。