在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!"
通过这些方法,你可以根据需要实现动态功能。