Home » Php » Why does PHP not have an attribute 'const' like C++ does?

Why does PHP not have an attribute 'const' like C++ does?

Posted by: admin July 12, 2020 Leave a comment


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?

How to&Answers:

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.


C++ is pretty unique (amongst C-family languages) to have such a notion of const. Quite simply, const and const-correctness are hard and consume time writing apparently repetitive overloads. That means that many languages which are intended to be simple to use- like say, pretty much all of them except C++- simply don’t view it as a worthwhile return on complexity.


You mean like constant class variables or just constants?

For argument pass-by-reference you can use &, but by default all objects in PHP are passed by reference so you only need to use it with basic types (int,float,string,bool,array)


PHP does have this.

global constants:


class constants: