coding-standard icon indicating copy to clipboard operation
coding-standard copied to clipboard

[Question] mark private properties as readonly in Constructor Property Promotion

Open mimmi20 opened this issue 2 years ago • 2 comments

There is the rule SlevomatCodingStandard.Classes.RequireConstructorPropertyPromotion.RequiredConstructorPropertyPromotion which enforces Constructor Property Promotion.

Is there an other (additional) rule that marks private properties as readonly?

For example:

    private array $config;

    public function __construct(array $config) {
        $this->config = $config;
    }

actually is converted to

    public function __construct(private array $config)
    {
        // nothing to do
    }

but also may be converted to

    public function __construct(private readonly array $config)
    {
        // nothing to do
    }

mimmi20 avatar Feb 06 '23 06:02 mimmi20

converting a non-readonly property to a readonly one would be wrong in that rule. This would be a behavior change for the class.

    public function __construct(private readonly array $config)
    {
        // nothing to do
    }

is the equivalent of

    private readonly array $config;

    public function __construct(array $config) {
        $this->config = $config;
    }

stof avatar Feb 23 '23 12:02 stof

Is there any rule to convert non readonly to readonly ? If so , please share link

kristijorgji avatar Dec 08 '23 16:12 kristijorgji