An interesting example is configuration variables.
For example: suppose a scenario where services are consumed, or an approval base, or production. These services come from a URL, which varies, depending on the database in question.
Thus, the URLs for these services can be determined by a flag that determines whether the application is in production mode or homologation. See the following example:
// variavel que define ambiente - homogação ou produção
$isHomolog = true;
// constantes para ambiente de homologação
const URL_SERVICO_1_HOMOLOG = "http://homolog1.com";
const URL_SERVICO_2_HOMOLOG = "http://homolog2.com";
// constantes para ambiente de produção
const URL_SERVICO_1_PRODUCTION = "http://production1.com";
const URL_SERVICO_2_PRODUCTION = "http://production2.com";
// constantes utilizadas para os serviços
const URL_SERVICO_1 = $isHomolog ? URL_SERVICO_1_HOMOLOG : URL_SERVICO_1_PRODUCTION;
const URL_SERVICO_2 = $isHomolog ? URL_SERVICO_2_HOMOLOG : URL_SERVICO_2_PRODUCTION;
In this example constants are defined for the approval and production environment. In addition, the variable $isHomolog
identifies whether the environment is type-approved (value true
) or production (value false
). Therefore, the service variables used by the system URL_SERVICO_1
and URL_SERVICO_2
have their value conditioned to the environment variable $isHomolog
.
The advantage of this mechanism is that there is no need to exchange multiple URLs in the system, depending on your environment: approval or production.
Note that the same behavior can be obtained with variables that are not constants, but the creation of constants guarantees that they will not be modified by the application. Note that this possibility of condition in its creation is not allowed after the constants are defined, which guarantees its correct use to the system.
Another interesting case is the concatenation of Strings to create a constants. in earlier versions of PHP, when trying to create String constants based on parts of other Strings, the following message is displayed: "PHP Parse error". Now this is allowed. This is exemplified in the link shown in the question itself. Here's an example:
// Constant declarations
const PHP = "PHP";
const LOBBY = "Lobby";
const PHPLOBBY = PHP . " " . LOBBY;
echo PHPLOBBY . "\n";
echo "\n=====================\n\n";
Notice that the PHPLOBBY constant is defined by a concatenation of Strings. This is useful when constants are used in the system, but concatenation is also used. In order to make the code cleaner, a constant being the result of several concatenation is often very useful. This kind of assignment to constants is already possible, in both Java and C # .NET.