What is the difference between using the constant () function and referencing a constant directly by name?

AS for the PHP manual constant()is useful if you need to get a constant value but not know its name. That is, it is stored in a variable or returned by a function.

define("MAXSIZE", 100);

echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line

If someone does not know MAXSIZEhow he can use . Is that enough to use ? Can someone explain an example? I tried the code below and it does not work. constant("MAXSIZE") echo MAXSIZE

    define("MAXSIZE", 100);

    $x = MAXSIZE;
    echo constant($x);
+3
source share
2 answers

Try it, you need to work

define("MAXSIZE", 100);

$x = "MAXSIZE";
echo constant($x);

The method constant()will return the value of a specific constant if you have a string variable.

Consider this example.

define("MAX", 1000);
define("MIN", 1);

$val = 50; 
$const = null;
if ( $val < 50 ) {
    $const = "MAX";
} else {
    $const = "MIN";
}

echo constant($const); // output 1
+9
source

, constant() (, variable) .

. , . , , , . constant() , , .

, :

define('MAXSIZE', 100);
echo MAXSIZE;

define('MAXSIZE-2', 100);

$sizeConstantPrefix = 'MAXSIZE';
$sizeConstantSuffix = '-2';

echo constant($sizeConstantPrefix.$sizeConstantSuffix);

class whatever {
   const 'MAXSIZE-2' = 100;
}

$className          = 'whatever'
$sizeConstantPrefix = 'MAXSIZE';
$sizeConstantSuffix = '-2';

echo constant($className.'::'.$sizeConstantPrefix.$sizeConstantSuffix);    
+2

All Articles