检查 php5 中声明函数中的变量是否为 null

check if variable null in declaring function in php5

我在声明函数时有这段代码我检查变量是否为空

使用这段代码我遇到了问题:

private function addDepartementField(FormInterface $form, ?Region $region) { .... }

问题是:

Parse Error: syntax error, unexpected '?', expecting variable (T_VARIABLE)

如何使用?在 php 5 中,我使用 php 5.6

感谢先进

在 PHP 5.6 中不可能。这是 PHP7.1 中的新功能。这就是您收到此错误的原因。

Type declarations for parameters and return values can now be marked as nullable by prefixing the type name with a question mark. This signifies that as well as the specified type, NULL can be passed as an argument, or returned as a value, respectively. http://php.net/manual/en/migration71.new-features.php

更新

唯一的事情是删除 ?,将 $region 默认设置为空 (Region $region = null) 或升级到 PHP7.*。 如果删除 ?,则必须传递一个 Region 实例。在我看来,这是一个更好的选择:avoiding null (What is the best alternative to null in object oriented programming?).