I'm sure the PHP elite will have so many problems with this solution but it does work (I'm using PHP 5.6) and honestly I don't care since I've done hacks far worst than this for prototyping in many of my Java projects.
function args_with_keys( array $args, $class = null, $method = null, $includeOptional = false )
{
if ( is_null( $class ) || is_null( $method ) )
{
$trace = debug_backtrace()[1];
$class = $trace['class'];
$method = $trace['function'];
}
$reflection = new ReflectionMethod( $class, $method );
if ( count( $args ) < $reflection->getNumberOfRequiredParameters() )
throw new RuntimeException( "Something went wrong! We had less than the required number of parameters." );
foreach ( $reflection->getParameters() as $param )
{
if ( isset( $args[$param->getPosition()] ) )
{
$args[$param->getName()] = $args[$param->getPosition()];
unset( $args[$param->getPosition()] );
}
else if ( $includeOptional && $param->isOptional() )
{
$args[$param->getName()] = $param->getDefaultValue();
}
}
return $args;
}
Using the PHP Reflections API, we get all the method parameters and align them with their numeric indexes. (There might be a better way to do that.)
To use simply type:
print_r( args_with_keys( func_get_args() ) );
I also added the ability to optionally return the method's optional parameters and values. I'm sure this solution is far from perfect, so you're mileage may vary. Do keep in mind that while I did make it so providing the class and method was optional, I do highly suggest that you specify them if you're going anywhere near a production environment. And you should try to avoid using this in anything other than a prototype setup to begin with.
Specify the class and method with:
print_r( args_with_keys( func_get_args(), __CLASS__, __FUNCTION__ ) );
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…