Reputation: 435
I want to detect parameters of a method is null or not in php. I use ReflectionParameter but it has strange behavior for detecting the type of parameter. Here's code I tested:
class myClass{
public function test($param2=null,$param1,$param3='something'){
echo "it's $param1";
if(!is_null($param2)){
echo "<br> it's $param2";
}
}
public function reflection(){
$reflection = new ReflectionMethod($this,'test');
$params = $reflection->getParameters();
echo '<pre> public function test($param2=null,$param1,$param3=\'something\'){}
<hr>';
#var_dump($params);
#echo '<hr>';
$this->reflection_parameter(0);
echo '<hr>';
$this->reflection_parameter(1);
echo '<hr>';
$this->reflection_parameter(2);
}
public function reflection_parameter($position){
$p = new ReflectionParameter(array($this,'test'),$position);
#var_dump($p->getPosition(),$p->getName(),$p->getDeclaringFunction());
var_dump('allowsNull()',$p->allowsNull());
var_dump('isOptional()',$p->isOptional());
#var_dump('isArray()',$p->isArray());
#var_dump('isCallable()',$p->isCallable());
var_dump('isDefaultValueAvailable()',$p->isDefaultValueAvailable());
#var_dump('getDefaultValue()',$p->getDefaultValue());
#var_dump('class',$p->getDeclaringClass()->name);
}
}
$refl= new myClass();
$refl->reflection();
I attached a screenshot of output: http://axgig.com/images/21110184497178611107.png
as you can see
public function test($param2=null,$param1,$param3='something')
param2 can be null but both of isOptional and isDefaultValueAvailable are false same as param1 that doesn't have any default value but for param3 it returns true
Now change first line of test function to:
public function test($param1,$param2=null,$param3='something')
and see output: http://axgig.com/images/85816853742428271329.png now isOptional and isDefaultValueAvailable are true for param2 while it false for previous usage
Upvotes: 0
Views: 266
Reputation: 23787
tl;dr: you cannot without parsing the raw php file yourself.
Yes. This is normal as you cannot omit a parameter in PHP when calling a function. All parameters until the last parameter which doesn't have a default aren't optional and their eventual default values are ignored.
Upvotes: 1