【问题标题】:check if variable null in declaring function in php5 [duplicate]检查php5中声明函数中的变量是否为null [重复]
【发布时间】:2017-05-16 08:48:19
【问题描述】:

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

这个代码我有问题:

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

问题是:

解析错误:语法错误,意外“?”,预期变量(T_VARIABLE)

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

感谢前辈

【问题讨论】:

  • 显示你的 php 5.6 版本代码
  • 关于 PHP 5.6 所能做的最好的事情,我认为类似于private function addDepartmentField(FormInterface $form = null, Region $region = null) { ... } - 通过给它一个默认值null,您可以将null 作为参数传递...或者当然把它排除在方法调用之外。

标签: php php-5.6


【解决方案1】:

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

现在可以通过在类型名称前加上问号来将参数和返回值的类型声明标记为可为空。这表示除了指定的类型外,NULL 也可以分别作为参数传递或作为值返回。 http://php.net/manual/en/migration71.new-features.php

更新

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

【讨论】:

  • 那么我的示例中的解决方案是什么??
  • 查看我的更新答案。我建议避免使用 null。
猜你喜欢
  • 2022-10-28
  • 2014-03-14
  • 2012-01-01
  • 2019-01-23
  • 1970-01-01
  • 2015-11-25
  • 2018-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多