suneesh
suneesh

Reputation: 304

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

AS per PHP manual constant() is useful if you need to retrieve the value of a constant, but do not know its name. I.e. 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 some one does not know MAXSIZE , how can he use constant("MAXSIZE"). Is that enough to use echo MAXSIZE ?. Can someone please explain with an example? I tried the below code and it doesn't work.

    define("MAXSIZE", 100);

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

Upvotes: 3

Views: 225

Answers (2)

Boaz
Boaz

Reputation: 20230

By do not know its name the manual means constant() can accept an expression (e.g a variable or a concatenation of a string and a variable) as the constant's name in addition to a string literal.

This description is indeed a bit misleading. A better way to describe this would be to say you don't have to know its name. For example, if you have the constant's name stored in a variable or defined by a class, you cannot reference the constant directly by name. This is where constant() comes in handy, allowing us to dynamically reference the constant's name without actually knowing it.

For example, consider the difference between:

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

and

define('MAXSIZE-2', 100);

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

echo constant($sizeConstantPrefix.$sizeConstantSuffix);

or the more extreme

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

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

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

Upvotes: 2

zzlalani
zzlalani

Reputation: 24354

Try this it, should work

define("MAXSIZE", 100);

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

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

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

Upvotes: 9

Related Questions