Home > Backend Development > PHP Tutorial > php如何定义一个可以接受null的函数

php如何定义一个可以接受null的函数

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
Release: 2016-06-06 20:50:51
Original
1193 people have browsed it

我定义一个接受String参数的函数,但是调用的时候传一个null进去,php会报一个fatal error,但实际情况确实会出现null参数的情况,我要定义一个即制定了参数类型,又可以接受null的函数该怎么做?

<?php function foo (String $arg) {
    return ;
}

foo(null);
Copy after login
Copy after login

执行如下

>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
Copy after login
Copy after login

回复内容:

我定义一个接受String参数的函数,但是调用的时候传一个null进去,php会报一个fatal error,但实际情况确实会出现null参数的情况,我要定义一个即制定了参数类型,又可以接受null的函数该怎么做?

<?php function foo (String $arg) {
    return ;
}

foo(null);
Copy after login
Copy after login

执行如下

>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
Copy after login
Copy after login

这样写,当你不提供参数的时候,参数默认是null

<?php function foo ($arg = null) {
    return ;
}

foo();
Copy after login

把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

手册里面已经说得很清楚了

Related labels:
php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template