PHP 7.4 错误:Typed property must not be accessed before initialization

Php 2021-06-09 阅读 326 评论 0

问题描述

在 PHP 7.4.6 中,使用以下代码:

<?php

class Test
{
    private string $foo;

    public function getFoo(): string
    {
        return $this->foo;
    }

    public function setFoo(string $foo): void
    {
        $this->foo = $foo;
    }
}

$test = new Test();
echo $test->getFoo() . PHP_EOL;

运行后,出现致命错误。

Fatal error: Uncaught Error: Typed property Test::$foo must not be accessed before initialization in /develop/test.php on line 9

Error: Typed property Test::$foo must not be accessed before initialization in /develop/test.php on line 9

Call Stack:
    0.0210     395056   1. {main}() /develop/test.php:0
    0.0855     395320   2. Test->getFoo() /develop/test.php:19

解决方法

PHP 7.4.0 起,类型声明可以用于函数的参数、返回值,还可以用于类的属性,来显性的指定需要的类型。

从未分配过的属性没有 null 值,但它处于一个 undefined 状态,永远不会匹配任何声明的 typeundefined !== null

1. 不使用属性类型

又回到以前 PHP 的写法,类属性不加类型声明。

class Test
{
    private $foo;
    public function getFoo()
    {
        return $this->foo;
    }
    public function setFoo($foo)
    {
        $this->foo = $foo;
    }
}

2. 给属性一个默认值

给属性一个默认值,空字符串或者其他字符串,但是不能使用 null 作为默认值。如下:

class Test
{
    private string $foo = "";
    ...
}

3. 定义属性为允许为空的类型

自 PHP 7.1.0 起,类型声明允许前置一个问号 (?) 用来声明这个值允许为指定类型,或者为 null

<?php

class Test
{
    private ?string $foo = null;
    public function getFoo(): ?string
    {
        return $this->foo;
    }
    public function setFoo(?string $foo): void
    {
        $this->foo = $foo;
    }
}
最后更新 2021-06-09