I'm looking for a sort of reversed func_get_args()
. I would like to find out how the parameters were named when function was defined. The reason for this is I don't want to repeat myself when using setting variables passed as arguments through a method:
public function myFunction($paramJohn, $paramJoe, MyObject $paramMyObject)
{
$this->paramJohn = $paramJohn;
$this->paramJoe = $paramJoe;
$this->paramMyObject = $paramMyObject;
}
Ideally I could do something like:
foreach (func_get_params() as $param)
$this->${$param} = ${$param};
}
Is this an overkill, is it a plain stupid idea, or is there a much better way to make this happen?
You could use
Reflection
:Since you're using this in a class, you can use
ReflectionMethod
instead ofReflectionFunction
:Here is a working example:
Where the above
var_dump()
prints:While it's not impossible to do it, it's usually better to use another method. Here is a link to a similar question on SO :
How to get a variable name as a string in PHP?
What you could do is pass all your parameters inside of an object, instead of passing them one by one. I'm assuming you are doing this in relation to databases, you might want to read about ORMs.
Code snippet that creates an array containing parameter names as keys and parameter values as corresponding values: