我们可以使用此功能根据某些数据结构自动将参数传递给我们的函数。
注意:我使用的是 php 8.0> 的名为“命名参数”的功能。
<?php
$valuesToProcess = [
'name' => 'Anderson Lucas Silva de Oliveira',
'age' => 21,
'hobbie' => 'Play games'
];
function processUserData($name, $age, $job = "", $hobbie = "")
{
$msg = "Hello $name. You have $age years old";
if (!empty($job)) {
$msg .= ". Your job is $job";
}
if (!empty($hobbie)) {
$msg .= ". Your hobbie is $hobbie";
}
echo $msg . ".";
}
$refFunction = new ReflectionFunction('processUserData');
$parameters = $refFunction->getParameters();
$validParameters = [];
foreach ($parameters as $parameter) {
if (!array_key_exists($parameter->getName(), $valuesToProcess) && !$parameter->isOptional()) {
throw new DomainException('Cannot resolve the parameter' . $parameter->getName());
}
if(!array_key_exists($parameter->getName(), $valuesToProcess)) {
continue;
}
$validParameters[$parameter->getName()] = $valuesToProcess[$parameter->getName()];
}
$refFunction->invoke(...$validParameters);
?>
结果为
Hello Anderson Lucas Silva de Oliveira. You have 21 years old. Your hobbie is Play games.