Class __construct 参数内的可见性(私有)- 这是有效的 php 代码吗?

Class visibility (private) inside __construct parameters - is this a valid php code?

我在看别人的代码,但我不明白。这是 class:

的例子
class ImageService
{
   public function __construct(
       private ImageTransformer $imageTransformer,
       private PostService $postService
   ) {

   }

   // other methods here
}

IDE 由于参数中的“private”而在 _construct 下显示错误。 我知道在 PHP 8 中有联合类型,但我找不到任何关于在 class 内部但在构造函数内部使用“private”或“public”的信息,以及这应该是什么做。我认为这是错字,它应该在 class 内,但是多个 classes 是这样创建的。这是有效代码还是有人不知道他在做什么?

这是 PHP 8.0.0 中的新功能,称为 Constructor Promotion

As of PHP 8.0.0, constructor parameters may also be promoted to correspond to an object property. It is very common for constructor parameters to be assigned to a property in the constructor but otherwise not operated upon. Constructor promotion provides a short-hand for that use case.

如果你execute that code你会看到。您应该检查您的 IDE 是否已更新以支持 PHP 8.0.0.