Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

php

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?

like image 925
Ed Heal Avatar asked Aug 30 '11 21:08

Ed Heal


People also ask

Can you define a constant in PHP?

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).

Why would someone choose to use a constant instead of a variable in their PHP script?

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.

What is the purpose of constant () function in PHP?

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.

How can we declare variable and constant in PHP?

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.


1 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.

like image 90
charley Avatar answered Oct 16 '22 12:10

charley