Dennis
Dennis

Reputation: 8101

Does PHP have a facility to reduce the duplication of parameter declaration and initialization in the class and the constructor?

Consider writing the class below:

class SomeClass
{

    /** @var array */
    private $files;

    /** @var string */
    private $productName;

    /** @var bool */
    private $singlePage;

    /** @var bool */
    private $signatureRequested;

    function __construct(array $files, string $productName, bool $singlePage, bool $signatureRequested = true)
    {
        $this->files = $files;
        $this->productName = $productName;
        $this->singlePage = $singlePage;
        $this->signatureRequested = $signatureRequested;
    }
}

$files, and other parameters are listed 4 times - you have to type the parameter name and then copy & paste it, or enter it 3 times into the above boiler template code. Is there a way to reduce the work it requires to type up all this code?

It seems to me like ideally I'd want something where I can specify the parameters I need to be initialized in the constructor just once, and some mechanism will go ahead and fill in the remaining boilerplate code.

Is there such a mechanism/code construct?

Upvotes: 2

Views: 69

Answers (2)

IMSoP
IMSoP

Reputation: 97718

Although the answer was "no" when this question was written, it is now "yes": Constructor Property Promotion was added in PHP 8.0 for exactly this purpose.

The way it works is that you list the property visibility inside the constructor signature, and it declares both the property and the parameter at the same time.

So your entire example would reduce down to this:

class SomeClass
{
    function __construct(
        private array $files,
        private string $productName,
        private bool $singlePage,
        private bool $signatureRequested = true
    ) { }
}

Upvotes: 3

Severin
Severin

Reputation: 1075

If you are using PHPStorm, you could have a look at:

PhpStorm shortcut to generate constructor params functionality

I can generate all that with a few simple shortcuts. I am sure other IDEs have the same feature.

Upvotes: 3

Related Questions