Declaring PHP Constants Based on a Condition

I use one separate file for all the constants of my PHP application.

class constants
{
    const USERNAME = 'abc';
    /*
      ⋮
    */
}

For let say USERNAMEconstant, the value can be either xyz, or abcbased on checking an existing file. If the xyz file exists USERNAME, the value will be xyz. How can I perform this check in a constant class?

+5
source share
4 answers

If the constant value is a variable, then this is not a constant, but a variable.

Since you are (correctly) trying to keep your applications and pushed aside from the global scope, you might be interested in the registry template. A registry is basically an illustrious array that stores everything you throw into it and is globally accessible throughout the application.

:


,

Runkit , , , , ( )

if ( file_exists('xyc') ) {
    runkit_constant_redefine('Constants::USERNAME', 'xyz');
}

( ):

class Abc { const FOO = 1; const BAR = 2; }
class Xyz extends Abc { const FOO = 2; }
class_alias(file_exists('abc') ? 'Abc' : 'Xyz', 'Constants');

Abc Xyz USERNAME (FOO ). , , , Constants::USERNAME, . , . PHP5.3.

-5.3 Constants , . abc_constants.php xyz_constants.php, , USERNAME xyz, include .

USERNAME , , . filecheck eval , .

: , .

+5

http://us2.php.net/manual/en/function.define.php

if ( $file_exists )
{
    define('MYCONSTANT', 'YEAH');
}
else
{
    define('MYCONSTANT', 'NOPE');
}
0
source

It is impossible to have conditional definitions of constants inside classes.

0
source

All Articles