Was wondering if it's possible to make a call like func_get_args()
(reference) but instead of resulting in a 0-index array, result in an associative array, using the variable names as the keys?
For example:
function foo($arg1, $arg2)
{
var_dump(func_get_args());
}
foo('bar1', 'bar2');
// Output
array(2) {
[0]=>
string(4) "bar1"
[1]=>
string(4) "bar2"
}
// Preferred
array(2) {
[arg1]=>
string(4) "bar1"
[arg2]=>
string(4) "bar2"
}
The reason I ask, is I need to validate that these args, passed as an array, to a RPC function, are actually populated. And it seems to be it's better to be specific about the contents rather than hoping they were passed in correct order:
// Now
if (array_key_exists(0, $args)) {
// Preferred
if (array_key_exists('arg1', $args)) {
It would be easy for me to create an assoc array from the args passed in to the original function before passing off to RPC, but was just wondering if there were an already compiled function to do it for me.
Thanks.
-- Edit --
Sorry, I forgot to mention that the code I am touching already exists, which means I cannot change the function signature.
You can make use of get_defined_vars
Docs at the very beginning of your function so that it contains only the passed (and defined) arguments:
function foo($arg1, $arg2)
{
var_dump(get_defined_vars());
}
foo('bar1', 'bar2');
Output (Demo):
array(2) {
["arg1"]=>
string(4) "bar1"
["arg2"]=>
string(4) "bar2"
}
If you're making use of static or global variables inside the function, specify them after you call get_defined_vars
, e.g.:
function foo($arg1, $arg2)
{
$passed = get_defined_vars();
static $staticVariable = 0;
global $staticVariable;
...
}
Take care that this is not the same as func_get_args
Docs which will also contain passed but not defined function arguments. Also default arguments aren't part of func_get_args
but naturally get_defined_vars
will have them with their default value.
You should require that the arguments themselves not be arguments, but rather, an associative array:
public function yourMethod(array $args = array()) {
if (array_key_exists('foo', $args)) {
// foo
}
// ...
}
$obj->yourMethod(array(
'foo' => 'foo value',
'bar' => 'bar value'
));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With