【问题标题】:Can I declare a typed property so that it accepts a null value as well?我可以声明一个类型化的属性,以便它也接受一个空值吗?
【发布时间】:2020-07-11 01:04:05
【问题描述】:

为什么会出现这个错误

Uncaught TypeError: Typed property $description must be string, null used

当我尝试将null 分配给类型化属性时?像这样:

new Foo(null);
class Foo
{
  private string $description;

  public function __construct($description)
  {
    $this->description = $description; // <-- Error on this line
  }
}

【问题讨论】:

  • 您将其定义为字符串。如果你不向构造函数传递任何东西,那么它将失败。
  • @FunkFortyNiner 没有完全不同的问题。我想让它成为一个字符串,但也允许为空。在 Java 中,您可以为 String 类型传入 null。
  • @Catfish 好吧。
  • 看起来 PHP 通过 ? 提供了可选类型。 private ?string $description 允许我传入一个字符串或 null。 php.net/manual/en/migration71.new-features.php

标签: php types type-hinting


【解决方案1】:

PHP 支持 nullable types,因为 PHP 7.1

如果您想声明一个属性以同时包含特定类型或null,请在类型声明前添加?

用你的例子:

class Foo
{
  private ?string $description;

  public function __construct(?string $description)
  {
    $this->description = $description;
  }
}

【讨论】:

    猜你喜欢
    • 2016-03-27
    • 2019-05-06
    • 2012-05-27
    • 2014-11-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-10
    • 2013-12-09
    相关资源
    最近更新 更多