以下代码:
class Type {
}
function foo(Type $t) {
}
foo(null);
运行时失败:
PHP致命错误:传递给foo()的参数1不能为空
为什么不允许像其他语言一样传递null ?
以下代码:
class Type {
}
function foo(Type $t) {
}
foo(null);
运行时失败:
PHP致命错误:传递给foo()的参数1不能为空
为什么不允许像其他语言一样传递null ?
当前回答
Try:
function foo(Type $t = null) {
}
查看PHP函数参数。
其他回答
正如前面提到的其他答案一样,这只有在指定null作为默认值时才有可能。
但是最干净的类型安全的面向对象的解决方案是NullObject:
interface FooInterface
{
function bar();
}
class Foo implements FooInterface
{
public function bar()
{
return 'i am an object';
}
}
class NullFoo implements FooInterface
{
public function bar()
{
return 'i am null (but you still can use my interface)';
}
}
用法:
function bar_my_foo(FooInterface $foo)
{
if ($foo instanceof NullFoo) {
// special handling of null values may go here
}
echo $foo->bar();
}
bar_my_foo(new NullFoo);
在我的情况下,问题是本机“修剪”函数,不接受null。 让我们假设你有这样的代码:
if (trim($tables) != '')
{
//code
}
PHP8会抛出这个错误;所以如果你正在处理遗留代码,我建议你创建一个自定义的“修剪”函数,就像这个,让它工作得更快。
public function custom_trim(?string $value)
{
return trim($value ?? '') ;
}
我真的很讨厌这个从7.4到8的变化
从PHP 8.0(2020年11月26日发布)开始,您还可以使用可空的联合类型。
这意味着你可以将Type或null作为参数值:
class Type {}
function foo(Type|null $param) {
var_dump($param);
}
foo(new Type()); // ok : object(Type)#1
foo(null); // ok : NULL
阅读更多关于联合类型的信息。
Try:
function foo(Type $t = null) {
}
查看PHP函数参数。
从PHP 7.1开始,可以使用可空类型,包括函数返回类型和参数。类型?T可以有指定类型T的值,或者null。
你的函数可以是这样的:
function foo(?Type $t)
{
}
只要您能够使用PHP 7.1,这种表示法就应该优于函数foo(Type $t = null),因为它仍然强制调用者显式地为形参$t指定一个参数。