Reputation: 51
Suppose I have this class:
class Test
{
public function foo($argument = "") {
//do something
}
public function bar($argument) {
//do something else
}
}
Is there any way I can tell if foo's argument is optional, and bar's argument isn't through PHP?
I've tried using getParameters() from ReflectionMethod, but that just returns the name, and not any information that can tell me if it is optional or not.
Upvotes: 1
Views: 161
Reputation: 5471
I am not entirely sure what you mean by detecting if function has optional argument.
But whats wrong with doing this ?
public function foo($argument = "") {
if($argument != "") {
.... argument is set
}
}
Edit: I see what you mean now. Yes you can use reflections for that
$reflection = new ReflectionMethod($className, $methodName);
$params = $reflection->getParameters();
foreach ($params as $param) {
echo $param->getName();
echo $param->isOptional();
}
Upvotes: 0
Reputation: 6319
With reflected methods getParameters
will return an array of ReflectionParameter
s. You can check the isOptional
method on ReflectionParameter
.
When you echo or print a ReflectionParameter
it will return its name.
Here's an example
Upvotes: 4