PHPverse 2025

Voting

The Note You're Voting On

hans at loltek dot net
1 year ago
I wanted an associative list of arguments, in case some else does too, I'm leaving it here.

I hope PHP gets native support for this, because a core implementation would be faster than this userland backtrace+reflection implementation:
<?php

/**
* Get function arguments as associative array
* (same as func_get_args() but with keys)
*
* @param bool $populateMissingArgumentsWithDefaults whether to populate the array with default values for missing arguments
*
* @return array
*/
function func_get_args_associative(bool $populateMissingArgumentsWithDefaults = false): array
{
$trace = debug_backtrace(0, 2)[1];
$reflection = null;
if (isset(
$trace['class'])) {
$reflection = new \ReflectionMethod($trace['class'], $trace['function']);
} else {
$reflection = new \ReflectionFunction($trace['function']);
}
$ret = [];
foreach (
$reflection->getParameters() as $param) {
if (
array_key_exists($param->getPosition(), $trace['args'])) {
$ret[$param->name] = $trace['args'][$param->getPosition()];
} elseif (
$populateMissingArgumentsWithDefaults) {
// because of the "required arguments declared after an optional argument are implicitly required" rule:
assert($param->isDefaultValueAvailable(), "i think all params are either in trace[args] or have default values");
$ret[$param->name] = $param->getDefaultValue();
}
}
return
$ret;
}
?>

<< Back to user notes page

To Top