note 128972 added to function.func-get-args

From: Date: Fri, 20 Oct 2023 09:34:39 +0000
Subject: note 128972 added to function.func-get-args
Groups: php.notes 
Request: Send a blank email to php-notes+get-220929@lists.php.net to get a copy of this message
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; } ?> ---- Server IP: 45.112.84.4 Probable Submitter: 45.91.157.134 (proxied: 84.49.158.188) ---- Manual Page -- https://php.net/manual/en/function.func-get-args.php Edit -- https://main.php.net/note/edit/128972 Del: integrated -- https://main.php.net/note/delete/128972/integrated Del: useless -- https://main.php.net/note/delete/128972/useless Del: bad code -- https://main.php.net/note/delete/128972/bad+code Del: spam -- https://main.php.net/note/delete/128972/spam Del: non-english -- https://main.php.net/note/delete/128972/non-english Del: in docs -- https://main.php.net/note/delete/128972/in+docs Del: other reasons-- https://main.php.net/note/delete/128972 Reject -- https://main.php.net/note/reject/128972 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#220929) next »