PHP 7.4类型化属性迭代

我刚刚发现了有关PHP 7.4的一些“奇怪的东西”,我不确定是我只是缺少了什么,还是可能是一个实际的错误。我通常对您的意见/确认感兴趣。

因此,在PHP中,您可以像这样遍历对象属性:

class DragonBallClass 
{
    public $goku;
    public $bulma = 'Bulma';
    public $vegeta = 'Vegeta';
}

$dragonBall = new DragonBallClass();

foreach ($dragonBall as $character) {
  var_dump($character);

}

RESULT

NULL
string(5) "Bulma"
string(6) "Vegeta"

现在,如果我们开始使用像这样的强类型属性:

class DragonBallClass 
{
    public string $goku;
    public string $bulma = 'Bulma';
    public string $vegeta = 'Vegeta';
}

$dragonBall = new DragonBallClass();

foreach ($dragonBall as $character) {
  var_dump($character);

}

我们将得到不同的结果:

string(5) "Bulma"
string(6) "Vegeta"

现在有什么不同:

When you DO NOT assign a default value to strongly typed property it will be of Uninitialized type. Which of course makes sense. The problem is though that if they end up like this you cannot loop over them they will simply be omitted - no error, no anything as you can see in the second example. So I just lose access to them.

这是有道理的,但请想象您有一个自定义的Request / Data类,如下所示:

namespace App\Request\Request\Post;

use App\Request\Request\Request;

class GetPostsRequest extends Request
{
    public string $title = '';
}

您看到丑陋的字符串分配了吗?如果我想使类的属性可迭代,则必须执行以下任一操作:

  • 跌落类型
  • 分配哑数值

我可能想要一个带有类型化属性的对象,其中没有任何值来遍历它们,并在可行时填充它们。

有什么更好的方法吗?是否可以选择保留类型并保持可枚举,而不必执行此伪值可憎性?