Why does PHP not have the moral equivalent to the C++ const
? I think that this is lacking in the PHP language. Is there a way to simulate the same properties as a const
object or parameter?
A constant is an identifier (name) for a simple value. The value cannot be changed during the script. A valid constant name starts with a letter or underscore (no $ sign before the constant name).
You use a CONSTANT when you know a value will never be changed. You use a variable when you want a value to be changed. You should use constants if you want to ensure that the value will not/cannot get changed anywhere after it's been defined.
constant() is useful if you need to retrieve the value of a constant, but do not know its name. I.e. it is stored in a variable or returned by a function. This function works also with class constants.
A constant can only be defined using define() function. It cannot be defined by any simple assignment. A variable can be defined by simple assignment (=) operator. There is no need to use the dollar ($) sign before constant during the assignment.
C# doesn't do the const
thing either, and it is a very general-purpose language.
I'm a big const
fan, but understand why scripts in scripting languages tend to not use them: Scripting languages are great for "running naked through the woods" because it is "fun", and very quick to add new functionality, because you are not enforcing serious type-correctness, including const
.
Perl and Python and Ruby use scalars for a reason, and pass/return arrays for a reason, because it is very easy to initially "grow" the system. Adding type correctness, including use of const
, can really slow down development iteration. Those languages were never intended to create "machined type-safe interfaces", and const
is the first thing you would do after you first got type-safety.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With