phpconstantspsr-1psr-12

PHP | define() vs. const


In PHP, you can declare constants in two ways:

  1. With define keyword

    define('FOO', 1);
    
  2. Using const keyword

    const FOO = 1;
    


Solution

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

    const FOO = 'BAR';
    define('FOO', 'BAR');
    

    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:

    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:

    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:

    class Foo {
        const BAR = 2; // Valid
    }
    // But
    class Baz {
        define('QUX', 2); // Invalid
    }
    

    Summary

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