如何在php中检测方法的参数为null


how to detect parameter of a method is null in php?

我想检测php中方法的参数是否为null。我使用ReflectionParameter,但它在检测参数类型时有奇怪的行为。这是我测试的代码:

 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();

我附上了一张输出的屏幕截图:http://axgig.com/images/21110184497178611107.png

正如你所看到的

public function test($param2=null,$param1,$param3='something')

param2可以为null,但isOptional和isDefaultValueAvailable都为false。与没有任何默认值的param1相同,但对于param3,它返回true

现在将测试功能的第一行更改为:

public function test($param1,$param2=null,$param3='something')

并参见输出:http://axgig.com/images/85816853742428271329.png现在isOptional和isDefaultValueAvailable对于param2为true,而对于以前的用法为false

tl;dr:如果不亲自解析原始php文件,就无法做到这一点。

是的。这是正常的,因为在调用函数时不能省略PHP中的参数。直到最后一个没有默认值的参数都不是可选的,它们的最终默认值将被忽略。