<?php if (! \function_exists('func_get_named_args')) { /** * Returns the arguments passed to the calling function, keyed by parameter name. * * Uses debug_backtrace and reflection to convert positional arguments * into an associative array keyed by the corresponding parameter names. * * See: https://gist.github.com/ghostwriter/82cffeb51b7052cba489f73a5350adf2 * * @return array<string, mixed> */ function func_get_named_args(): array { $caller = debug_backtrace(0, 2)[1]; $arguments = $caller['args'] ?? []; $reflectionMethod = isset($caller['class']) ? new ReflectionMethod($caller['class'], $caller['function']) : new ReflectionFunction($caller['function']); foreach ($reflectionMethod->getParameters() as $parameter) { $position = $parameter->getPosition(); if (isset($arguments[$position])) { $arguments[$parameter->getName()] = $arguments[$position]; unset($arguments[$position]); } } return $arguments; } } function callFunc(...$params) { $argv = func_get_named_args(); $argc = count($argv); print_r([ '$argc' => $argc, '$argv' => $argv, ]); } class User { public function register($email, $password, $active = null, $default = 0, ...$attributes) { $argv = func_get_named_args(); $argc = count($argv); print_r([ '$argc' => $argc, '$argv' => $argv, ]); return [$email, $password, $attributes]; } } $foo = new User(); $foo->register('admin@test.com', 'pass1', ...[ 'id' => 'uuid-1', 'phone' => '012-345-6789', 'role' => 'admin', ]); echo PHP_EOL . '--------' . PHP_EOL; callFunc(...[ 'id' => 'uuid-2', 'email' => 'test@test.com', 'phone' => '987-654-3210', 'name' => 'first last2', 'role' => 'tester', 'password' => 'pass2' ]);
You have javascript disabled. You will not be able to edit any code.