Skip to content
Advertisement

PHP | define() vs. const

In PHP, you can declare constants in two ways:

  1. With define keyword

    JavaScript
  2. Using const keyword

    JavaScript

  • What are the main differences between those two?
  • When and why should you use one and when use the other?

Advertisement

Answer

As of PHP 5.3 there are two ways to define constants: Either using the const keyword or using the define() function:

JavaScript

The fundamental difference between those two ways is that const defines constants at compile time, whereas define defines them at run time. This causes most of const‘s disadvantages. Some disadvantages of const are:

  • const cannot be used to conditionally define constants. To define a global constant, it has to be used in the outermost scope:

    JavaScript

    Why would you want to do that anyway? One common application is to check whether the constant is already defined:

    JavaScript
  • const accepts a static scalar (number, string or other constant like true, false, null, __FILE__), whereas define() takes any expression. Since PHP 5.6 constant expressions are allowed in const as well:

    JavaScript
  • const takes a plain constant name, whereas define() accepts any expression as name. This allows to do things like this:

    JavaScript
  • consts are always case sensitive, whereas define() allows you to define case insensitive constants by passing true as the third argument (Note: defining case-insensitive constants is deprecated as of PHP 7.3.0 and removed since PHP 8.0.0):

    JavaScript

So, that was the bad side of things. Now let’s look at the reason why I personally always use const unless one of the above situations occurs:

  • const simply 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.

  • const defines a constant in the current namespace, while define() has to be passed the full namespace name:

    JavaScript
  • Since PHP 5.6 const constants can also be arrays, while define() does not support arrays yet. However, arrays will be supported for both cases in PHP 7.

    JavaScript

Finally, note that const can also be used within a class or interface to define a class constant or interface constant. define cannot be used for this purpose:

JavaScript

Summary

Unless you need any type of conditional or expressional definition, use consts instead of define()s – simply for the sake of readability!

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement