Search code examples
phpphp-8

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


I'm looking at some one else's code that I do not understand. This is example of class:

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

   }

   // other methods here
}

IDE is showing errors under _construct due to "private" inside params. I know that in PHP 8 there are union types, but I cannot find any info about using "private" or "public" not inside class but inside constructor, and what this supposed to do. I thought that this is typo, and it supposed to be inside class, but multiple classes are created like this. Is this a valid code or someone does not know what is he doing?


Solution

  • This is new in PHP 8.0.0 and is called 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.

    If you execute that code you will see. You should check to see if your IDE has been updated to support PHP 8.0.0.