php如何定义一个可以接受null的函数
Jun 06, 2016 pm 08:50 PM
我定义一个接受String参数的函数,但是调用的时候传一个null进去,php会报一个fatal error,但实际情况确实会出现null参数的情况,我要定义一个即制定了参数类型,又可以接受null的函数该怎么做?
<?php function foo (String $arg) { return ; } foo(null);
执行如下
>php t.php Catchable fatal error: Argument 1 passed to foo() must be an instance of String, null given, called in /Users/jiajun/t.php on line 7 and defined in /Users/jiajun/t.php on line 3
回复内容:
我定义一个接受String参数的函数,但是调用的时候传一个null进去,php会报一个fatal error,但实际情况确实会出现null参数的情况,我要定义一个即制定了参数类型,又可以接受null的函数该怎么做?
<?php function foo (String $arg) { return ; } foo(null);
执行如下
>php t.php Catchable fatal error: Argument 1 passed to foo() must be an instance of String, null given, called in /Users/jiajun/t.php on line 7 and defined in /Users/jiajun/t.php on line 3
这样写,当你不提供参数的时候,参数默认是null
<?php function foo ($arg = null) { return ; } foo();
把String修饰去掉就行了。
如果你一定需要判断参数类型,可以用 is_string($arg) 来判断。
http://www.php.net/manual/en/language...
if NULL is used as the default parameter value, it will be allowed as an argument for any later call
手册里面已经说得很清楚了

인기 기사

인기 기사

뜨거운 기사 태그

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











Ubuntu 및 Debian용 PHP 8.4 설치 및 업그레이드 가이드

PHP 개발을 위해 Visual Studio Code(VS Code)를 설정하는 방법
