Skip to content

Establish Symfony coding standards for private readonly properties and readonly classes #57602

@ghost

Description

Description

AFAIR, when Symfony bumped the minimum PHP version to 8.1 and people started using private readonly properties in pull requests the response from the core team was negative. I even remember a comment from @nicolas-grekas who said that private readonly properties don't make sense.
Now I can see that we have 257 occurences https://github.com/search?q=repo%3Asymfony%2Fsymfony+%22private+readonly%22&type=code.

I fully agree that private readonly properties do not make sense and only make visual noise. I think people don't understand why this keyword was introduced to the language (I bet 99% don't read RFCs, only New Features section 😄) and started using it everywhere when they expect a property to be set once, doesn't matter it's a private api, so this keyword became more like a validation/protection use case.
What's more, 99.9% of private readonly properties are dependencies. Have you ever override a property that holds a dependency?

The same goes for readonly classes. Readonly on the class indicates a class is, surprise, readonly. But it makes sense only for structures like DTOs, VO etc. For classes that do a job, i.e. so called services, the readonly keyword doesn't make sense. You don't read anything from this class because they are not designed for reading (by "reading" I mean reading properties, not methods that return some data).

I think having a standard would be nice at least for consistency, otherwise some code will have private readonly properties and some not.
Please add a comment if you vote 👎.

P.S. I bet the readonly keyword would have never been introduced to the PHP if we has asymmetric visibility already.

Reference:
NIcolas' feedback on private readonly properties:
#46674 (comment)
#53279 (comment)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions