(PHP 4 >= 4.0.4, PHP 5)
constant — 返回一个常量的值
通过 name
返回常量的值。
当你不知道常量名,却需要获取常量的值时, constant() 就很有用了。也就是常量名储存在一个变量里,或者由函数返回常量名。
该函数也适用 class constants。
name
常量名。
返回常量的值。如果常量未定义则返回 NULL
。
如果常量未定义,会产生一个 E_WARNING
级别的错误。
Example #1 constant() 的例子
<?php
define("MAXSIZE", 100);
echo MAXSIZE;
echo constant("MAXSIZE"); // same thing as the previous line
interface bar {
const test = 'foobar!';
}
class foo {
const test = 'foobar!';
}
$const = 'test';
var_dump(constant('bar::'. $const)); // string(7) "foobar!"
var_dump(constant('foo::'. $const)); // string(7) "foobar!"
?>
Richard J. Turner (2013-01-31 11:57:44)
As of PHP 5.4.6 constant() pays no attention to any namespace aliases that might be defined in the file in which it's used. I.e. constant() always behaves as if it is called from the global namespace. This means that the following will not work:
<?php
class Foo {
const BAR = 42;
}
?>
<?php
namespace Baz;
use \Foo as F;
echo constant('F::BAR');
?>
However, calling constant('Foo::BAR') will work as expected.
adam at adamhahn dot com (2011-09-28 12:59:29)
This function is namespace sensitive when calling class constants.
Using:
<?php namespace sub;
class foo {
const BAR = 'Hello World';
}
constant('foo::BAR'); // Error
constant('sub\foo::BAR'); // works
?>
This does not seem to affect constants defined with the 'define' function. Those all end up defined in the root namespace unless another namespace is implicitly defined in the string name of the constant.
Anonymous (2011-03-07 18:59:43)
You can get the value of class and interface constants using this function.
<?php
interface IDatabase {
const Test = 22;
}
class MyDatabase implements IDatabase {
}
echo constant('MyDatabase::Test'); # Outputs 22
echo constant('IDatabase::Test'); # Also outputs 22
?>
bohwaz (2010-07-05 06:28:59)
Return constants from an object. You can filter by regexp or match by value to find a constant name from the value.
Pretty useful sometimes.
<?php
function findConstantsFromObject($object, $filter = null, $find_value = null)
{
$reflect = new ReflectionClass($object);
$constants = $reflect->getConstants();
foreach ($constants as $name => $value)
{
if (!is_null($filter) && !preg_match($filter, $name))
{
unset($constants[$name]);
continue;
}
if (!is_null($find_value) && $value != $find_value)
{
unset($constants[$name]);
continue;
}
}
return $constants;
}
?>
Examples :
<?php
class Example
{
const GENDER_UNKNOW = 0;
const GENDER_FEMALE = 1;
const GENDER_MALE = 2;
const USER_OFFLINE = false;
const USER_ONLINE = true;
}
$all = findConstantsFromObject('Example');
$genders = findConstantsFromObject('Example', '/^GENDER_/');
$my_gender = 1;
$gender_name = findConstantsFromObject('Example', '/^GENDER_/', $my_gender);
if (isset($gender_name[0]))
{
$gender_name = str_replace('GENDER_', '', key($gender_name));
}
else
{
$gender_name = 'WTF!';
}
?>
hellekin (2010-05-25 08:07:43)
Checking if a constant is empty is bork...
You cannot
<?php
define('A', '');
define('B', 'B');
if (empty(B)) // syntax error
if (empty(constant('B'))) // fatal error
// so instead, thanks to LawnGnome on IRC, you can cast the constants to boolean (empty string is false)
if (((boolean) A) && ((boolean) B))
// do stuff
?>
dachnik (2010-04-09 23:41:55)
You can define values in your config file using the names of your defined constants, e.g.
in your php code:
define("MY_CONST",999);
in you config file:
my = MY_CONST
When reading the file do this:
$my = constant($value); // where $value is the string "MY_CONST"
now $my holds the value of 999
roller (2009-06-21 08:21:34)
howto echo CONSTANT_NAME without warnings and "if " checking:
<?php
!defined("CONSTANT_NAME") || constant("CONSTANT_NAME");
?>
cory dot mawhorter @ ephective dot com (2008-09-08 14:08:48)
This is how I check to see if a bool constant is true:
<?php
function consttrue($const) {
return !defined($const) ? false : constant($const);
}
?>
Examples
<?php
var_dump(consttrue('UNDEFINED_CONST'));
define('SOME_CONST', true);
var_dump(consttrue('SOME_CONST'));
define('SOME_CONST2', false);
var_dump(consttrue('SOME_CONST2'));
?>
Returns
bool(false)
bool(true)
bool(false)
If it isn't defined it will return false, otherwise it will return the value of the constant... which would be either true/false depending on what you set it to.
Joachim Chmielewski (2008-02-15 03:34:07)
To use constants in functions additional its not neccessary to change the function call wherever you need the constant in a function.
foo($var1);
to
foo($var1,$const);
More easy is to change the function definition and use a default value for a new variable that contains the const value.
function foo($var1,$my_const=CONST_VALUE){
if($my_const==1) dosomething();
}
Now it`s not necessary to change the function call wherever you need the function.
vgr at europeanexperts dot org (2007-03-01 05:57:12)
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<br>";
[/code]
If you want, you can see a demonstration at http://www.fecj.org/extra/test_constants.php
Regards
(2007-02-01 20:29:30)
@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') {
// ...
}
?>
XC (2007-01-19 02:13:03)
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.
(2006-10-03 17:17:49)
If the constant does not exist, constant() will generate a warning and return null.
narada dot sage at googlemail dot com (2006-07-13 06:01:17)
To access the value of a class constant use the following technique.
<?php
class a {
const b = 'c';
}
echo constant('a::b');
// output: c
?>
service at dual-creators dot de (2006-05-16 10:00:57)
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
Trevor Blackbird > yurab.com (2006-04-18 14:58:53)
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 at hotmail dot com (2005-11-26 00:39:34)
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);
}
}
(2005-10-11 07:20:21)
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.
Joachim Kruyswijk (2004-11-13 09:12:52)
The constant name can be an empty string.
Code:
define("", "foo");
echo constant("");
Output:
foo
VGR_experts_exchange at edainworks dot com (2003-09-19 05:32:21)
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'))) {}
?>
Andre (2003-04-27 13:10:37)
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;
}
?>