Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 464
Phil Avatar asked Jun 19 '26 23:06

Phil


1 Answers

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

like image 60
Phil Avatar answered Jun 21 '26 15:06

Phil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!