In PHP, you can declare constants in two ways:
-
With
definekeyworddefine('FOO', 1); -
Using
constkeywordconst FOO = 1;
- What are the main differences between those two?
- When and why should you use one and when use the other?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
As of PHP 5.3 there are two ways to define constants: Either using the
constkeyword or using thedefine()function:The fundamental difference between those two ways is that
constdefines constants at compile time, whereasdefinedefines them at run time. This causes most ofconst‘s disadvantages. Some disadvantages ofconstare:constcannot be used to conditionally define constants. To define a global constant, it has to be used in the outermost scope:Why would you want to do that anyway? One common application is to check whether the constant is already defined:
constaccepts a static scalar (number, string or other constant liketrue,false,null,__FILE__), whereasdefine()takes any expression. Since PHP 5.6 constant expressions are allowed inconstas well:consttakes a plain constant name, whereasdefine()accepts any expression as name. This allows to do things like this:consts are always case sensitive, whereasdefine()allows you to define case insensitive constants by passingtrueas the third argument (Note: defining case-insensitive constants is deprecated as of PHP 7.3.0 and removed since PHP 8.0.0):So, that was the bad side of things. Now let’s look at the reason why I personally always use
constunless one of the above situations occurs:constsimply reads nicer. It’s a language construct instead of a function and also is consistent with how you define constants in classes.const, being a language construct, can be statically analysed by automated tooling.constdefines a constant in the current namespace, whiledefine()has to be passed the full namespace name:Since PHP 5.6
constconstants can also be arrays, whiledefine()does not support arrays yet. However, arrays will be supported for both cases in PHP 7.Finally, note that
constcan also be used within a class or interface to define a class constant or interface constant.definecannot be used for this purpose:Summary
Unless you need any type of conditional or expressional definition, use
consts instead ofdefine()s – simply for the sake of readability!