use define () unless you consider readability, class constants, or focus on micro-optimizations
In PHP, it is customary to use the Define () function to define constants. But starting at some point, PHP can also use the const keyword to declare constants. So when you define constants, which way do you use them?
The answer lies in the difference between the two methods. Define () defines constants during the execution period, while Const defines constants at compile time. The const has a slight speed advantage, but it's not worth considering unless you're building a massive software. Define () puts a constant into the global scope, although you can include namespaces in the constant name. This means that you cannot use define () to define class constants. Define () allows you to use an expression in a constant name and a constant value, but no const is allowed. This makes define () more flexible. Define () can be invoked in the if () code block, but not const.
Example
<?php//Let ' s and how the two methods treat namespaces namespace;
Const GIMLI_ID = 1;
Define (' middleearth\creatures\elves\legolas_id ', 2); Echo (\middleearth\creatures\dwarves\gimli_id); 1 echo (\middleearth\creatures\elves\legolas_id); 2;
Note This we used define ()//Now let's declare some bit-shifted constants representing ways to enter Mordor. Define (' transport_method_sneaking ', 1 << 0);
Ok! Const TRANSPORT_METHOD_WALKING = 1 << 1; Compile error!
Const can ' t use expressions as values//Next, conditional constants.
Define (' hobbits_frodo_id ', 1);
if ($isGoingToMordor) {define (' Transport_method ', transport_method_sneaking);//ok! Const PARTY_LEADER_ID = hobbits_frodo_id//Compile error:const can ' t be used into an if block}//Finally, Class Constan
TS class onering{Const MELTING_POINT_DEGREES = 1000000;//ok! Define (' Show_elvish_degrees ', 200);
Compile Error:can ' t use define () within a class}?>
Because define () is more flexible, you should use it to avoid some headaches unless you explicitly need class constants. Using const usually produces more readable code, but at the expense of flexibility.
Whichever you choose, please keep it in line.