We can use this functionality to automatically pass arguments to our function based on some data structure.
NOTE: I am using a php 8.0> feature called "Nameds parameter".
<?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);
?>
Results in:
Hello Anderson Lucas Silva de Oliveira. You have 21 years old. Your hobbie is Play games.