What are the main differences between const vs define

Technology CommunityCategory: PHPWhat are the main differences between const vs define
VietMX Staff asked 4 years ago

The fundamental difference between const vs define is that const defines constants at compile time, whereas define defines them at run time.

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

// but
if (...) {
    const FOO = 'BAR';    // Invalid
}
if (...) {
    define('FOO', 'BAR'); // Valid
}

Also until PHP 5.3, const could not be used in the global scope. You could only use this from within a class. This should be used when you want to set some kind of constant option or setting that pertains to that class. Or maybe you want to create some kind of enum. An example of good const usage is to get rid of magic numbers.

Define can be used for the same purpose, but it can only be used in the global scope. It should only be used for global settings that affect the entire application.

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