Search code examples
phppropertiesconstantsphp-8.1

PHP Readonly Properties or Constants?


Since PHP 8.1 the native support for readonly properties arrived. But we already have constants with visibilities.

Please help me to answer these two questions:

  1. Which differences are between using constants and properties?
  2. When to use which one?

Solution

  • Difference in write

    One big difference is that you can't set class constants dynamically at runtime, which you can do with readonly properties (from the constructor).

    Difference in read

    There's also a big difference in how you access the two. Unless the property is static, you will need to have an instance (and all instances can have different values), while constants can always be access without an instance.

    Props to M. Eriksson