Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Miscellaneous Functions : constant

constant

Returns the value of a constant (PHP 4 >= 4.0.4, PHP 5)
mixed constant ( string name )

Return the value of the constant indicated by name.

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.

This function works also with class constants.

Parameters

name

The constant name.

Return Values

Returns the value of the constant, or NULL if the constant is not defined.

Examples

Example 1351. constant() example

<?php

define
("MAXSIZE", 100);

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

?>


See Also
define()
defined()
The section on Constants

Related Examples ( Source code ) » constant







Code Examples / Notes » constant

xc

When you often write lines like
<?php
if(defined('FOO') && constant('FOO') === 'bar')
{
...
}
?>
to prevent errors, you can use the following function to get the value of a constant.
<?php
function getconst($const)
{
return (defined($const)) ? constant($const) : null;
}
?>
Finally you can check the value with
<?php
if(getconst('FOO') === 'bar')
{
...
}
?>
It's simply shorter.


narada dot sage

To access the value of a class constant use the following technique.
<?php
class a {
   const b = 'c';
}
echo constant('a::b');
// output: c
?>


joachim kruyswijk

The constant name can be an empty string.
Code:
define("", "foo");
echo constant("");
Output:
foo


trevor blackbird > yurab.com

Technically you can define constants with names that are not valid for variables:
<?php
// $3some is not a valid variable name
// This will not work
$3some = 'invalid';
// This works
define('3some', 'valid');
echo constant('3some');
?>
Of course this is not a good practice, but PHP has got you covered.


timneill

Please note when using this function from within a class to retrieve a php5 class constant, ensure you include the 'self::'.
class Validate
{
const TEXT_MAX = 65536;

//-- this will work
public static function textWORKS($_value, $_type = 'TEXT')
{
$_max = constant('self::' . $_type . '_MAX');
return (strlen($_value) <= $_max ? true : false);
}

//-- this will fail
public static function textFAILS($_value, $_type = 'TEXT')
{
//-- Debug Warning: constant(): Couldn't find constant TEXT_MAX
$_max = constant($_type . '_MAX');
return (strlen($_value) <= $_max ? true : false);
}
}


andre

Maybe this is useful:
$file_ext is the file Extension of the image
<?php
if ( imagetypes() & @constant('IMG_' . strtoupper($file_ext)) )
{
   $file_ext = $file_ext == 'jpg' ? 'jpeg' : $file_ext;
   $create_func = 'ImageCreateFrom' . $file_ext;
}
?>


service

It's easily to user constant() and define() to translate some words from your database-saves.
For example:
You have a table userprofil and one coloumn is "gender".
Gender can be male or female but you will display "maennlich" or "weiblich" (german words for it - whatever...)
First step: Fetch into $Gender
Second:
define("male", "maennlich");
define("female", "weiblich");
Third:
echo constant($Gender);
Now, the index of the variable $Gender will be handled like a constant!
(It works like "echo male;" for better understanding)
And a result of this, it displays maennlich btw. weiblich!
greetz


11-oct-2005 03:20

In reply to VGR_experts_exchange at edainworks dot com
To check if a constant is boolean, use this instead:
<?php
if (TRACE === true)  {}
?>
Much quicker and cleaner than using defined() and constant() to check for a simple boolean.
IMO, using ($var === true) or ($var === false) instead of ($var) or (!$var) is the best way to check for booleans no matter what. Leaves no chance of ambiguity.


vgr

in reply to anonymous
[quote]
To check if a constant is boolean, use this instead:
<?php
if (TRACE === true)  {}
?>
Much quicker and cleaner than using defined() and constant() to check for a simple boolean.
[/quote]
is definitely nor cleaner (because it's still as wrong as using simply "if (TRACE)") nor quicker than " if (TRACE)" (one more comparison on a boolean value). This will generate PHP errors. The constant TRACE is NOT defined.
error :
PHP Notice:  Use of undefined constant TRACE - assumed 'TRACE' in yourpath/test_constants.php on line 5
if you really want to be "clean" and as quick as possible, then there is a function :
[code]
function IsBooleanConstantAndTrue($constname) { // : Boolean
 $res=FALSE;
 if (defined($constname)) $res=(constant($constname)===TRUE);
 return($res);
}
// use : if (IsBooleanConstantAndTrue('TRACE')) echo "trace is really True
";
[/code]
If you want, you can see a demonstration at http://www.fecj.org/extra/test_constants.php
Regards


04-oct-2006 01:17

If the constant does not exist, constant() will generate a warning and return null.

vgr_experts_exchange

Hello. This applies to constants being defined as Boolean values, and may-be applies generally.
I advise you to NOT use this in an included file, in a function or elsewhere outside the scope where the define('TRACE',TRUE) is placed) :
if (TRACE) {}
This will always evaluate to TRUE if the constant is not defined previously (the story about this becoming an string 'TRACE', thus evaluating to TRUE)
Use this :
<?php
if ((defined('TRACE'))AND(constant('TRACE')))  {}
?>


02-feb-2007 04:29

@XC:
That isn't necessary. If a constant is undefined, constant() returns NULL; simply suppressing the warning should be enough:
<?php
if(defined('FOO') && constant('FOO') === 'bar'){
// ...
}
?>
becomes
<?php
if(@constant('FOO') === 'bar') {
// ...
}
?>
Note that in the first snippet, the call to constant isn't unnecessary as well, and adds a bit of overhead. If you're set on using the first notation, the following is better:
<?php
if(defined('FOO') && FOO === 'bar') {
// ...
}
?>


Change Language


Follow Navioo On Twitter
connection_aborted
connection_status
connection_timeout
constant
define
defined
die
eval
exit
get_browser
__halt_compiler
highlight_file
highlight_string
ignore_user_abort
pack
php_check_syntax
php_strip_whitespace
show_source
sleep
sys_getloadavg
time_nanosleep
time_sleep_until
uniqid
unpack
usleep
eXTReMe Tracker