constant
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 and enum cases.
Parameters
Return Values
Returns the value of the constant.
Errors/Exceptions
If the constant is not defined, an Error exception is thrown. Prior to PHP 8.0.0, an E_WARNING level error was generated in that case.
Changelog
Version | Description |
---|---|
8.0.0 | If the constant is not defined, constant() now throws an Error exception; previously an E_WARNING was generated, and null was returned. |
Examples
Example #1 Using constant() with Constants
echo MAXSIZE ;
echo constant ( «MAXSIZE» ); // same thing as the previous line
interface bar const test = ‘foobar!’ ;
>
class foo const test = ‘foobar!’ ;
>
var_dump ( constant ( ‘bar::’ . $const )); // string(7) «foobar!»
var_dump ( constant ( ‘foo::’ . $const )); // string(7) «foobar!»
Example #2 Using constant() with Enum Cases (as of PHP 8.1.0)
enum Suit
case Hearts ;
case Diamonds ;
case Clubs ;
case Spades ;
>
var_dump ( constant ( ‘Suit::’ . $case )); // enum(Suit::Hearts)
See Also
- define() — Defines a named constant
- defined() — Checks whether a given named constant exists
- get_defined_constants() — Returns an associative array with the names of all the constants and their values
- The section on Constants
User Contributed Notes 17 notes
The constant name can be an empty string.
If you are referencing class constant (either using namespaces or not, because one day you may want to start using them), you’ll have the least headaches when doing it like this:
class Foo const BAR = 42 ;
>
?>
namespace Baz ;
use \ Foo as F ;
echo constant ( F ::class. ‘::BAR’ );
?>
since F::class will be dereferenced to whatever namespace shortcuts you are using (and those are way easier to refactor for IDE than just plain strings with hardcoded namespaces in string literals)
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:
echo constant ( ‘F::BAR’ );
?>
However, calling constant(‘Foo::BAR’) will work as expected.
It is worth noting, that keyword ‘self’ can be used for constant retrieval from within the class it is defined
class Foo const PARAM_BAR = ‘baz’ ;
public function getConst ( $name ) return constant ( «self:: < $name >» );
>
>
$foo = new Foo ();
echo $foo -> getConst ( ‘PARAM_BAR’ ); // prints ‘baz’
?>
Technically you can define constants with names that are not valid for variables:
// $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.
$file_ext is the file Extension of the image
When you often write lines like
if( defined ( ‘FOO’ ) && constant ( ‘FOO’ ) === ‘bar’ )
.
>
?>
to prevent errors, you can use the following function to get the value of a constant.
function getconst ( $const )
return ( defined ( $const )) ? constant ( $const ) : null ;
>
?>
Finally you can check the value with
To access the value of a class constant use the following technique.
In reply to VGR_experts_exchange at edainworks dot com
To check if a constant is boolean, use this instead:
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.
Checking if a constant is empty is bork.
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
?>
This function is namespace sensitive when calling class constants.
class foo const BAR = ‘Hello World’ ;
>
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.
define ( __NAMESPACE__ . ‘\Bar’ , ‘its work’ ); // ..but IDE may make notice
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
Return constants from an object. You can filter by regexp or match by value to find a constant name from the value.
function findConstantsFromObject ( $object , $filter = null , $find_value = null )
$reflect = new ReflectionClass ( $object );
$constants = $reflect -> getConstants ();
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!’ ;
>
The use of constant() (or some other method) to ensure the your_constant was defined is particularly important when it is to be defined as either `true` or `false`.
If `BOO` did NOT get defined as a constant, for some reason,
would evaluate to `TRUE` and run anyway. A rather unexpected result.
The reason is that PHP ASSUMES you «forgot» quotation marks around `BOO` when it did not see it in its list of defined constants.
So it evaluates: `if (‘BOO’)`.
Since every string, other than the empty string, is «truthy», the expression evaluates to `true` and the do_something() is run, unexpectedly.
then if `BOO` has not been defined, `constant(BOO)` evaluates to `null`,
which is falsey, and `if (null)`. becomes `false`, so do_something() is skipped, as expected.
The PHP behavior regarding undefined constants is particularly glaring when having a particular constant defined is the exception, «falsey» is the default, and having a «truthy» value exposes a security issue. For example,
.
Note that only the version using `defined()` works without also throwing a PHP Warning «error message.»
(disclosure: I also submitted an answer to the SO question linked to above)
Php class const string
Константы также могут быть объявлены в пределах одного класса. Область видимости констант по умолчанию public .
Замечание:
Константы класса могут быть переопределены дочерним классом. Начиная с PHP 8.1.0, константы класса не могут быть переопределены дочерним классом, если он определён как окончательный (final).
Интерфейсы также могут содержать константы . За примерами обращайтесь к разделу об интерфейсах.
К классу можно обратиться с помощью переменной. Значение переменной не может быть ключевым словом (например, self , parent и static ).
Обратите внимание, что константы класса задаются один раз для всего класса, а не отдельно для каждого созданного объекта этого класса.
Пример #1 Объявление и использование константы
class MyClass
const CONSTANT = ‘значение константы’ ;
?php
function showConstant () echo self :: CONSTANT . «\n» ;
>
>
echo MyClass :: CONSTANT . «\n» ;
$classname = «MyClass» ;
echo $classname :: CONSTANT . «\n» ;
$class = new MyClass ();
$class -> showConstant ();
Специальная константа ::class , которой на этапе компиляции присваивается полное имя класса, полезна при использовании с классами, использующими пространства имён.
Пример #2 Пример использования ::class с пространством имён
Пример #3 Пример констант, заданных выражением
class foo const TWO = ONE * 2 ;
const THREE = ONE + self :: TWO ;
const SENTENCE = ‘Значение константы THREE — ‘ . self :: THREE ;
>
?>
Пример #4 Модификаторы видимости констант класса, начиная с PHP 7.1.0
class Foo public const BAR = ‘bar’ ;
private const BAZ = ‘baz’ ;
>
echo Foo :: BAR , PHP_EOL ;
echo Foo :: BAZ , PHP_EOL ;
?>?php
Результат выполнения данного примера в PHP 7.1:
bar Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …
Замечание:
Начиная с PHP 7.1.0 для констант класса можно использовать модификаторы области видимости.
User Contributed Notes 12 notes
it’s possible to declare constant in base class, and override it in child, and access to correct value of the const from the static method is possible by ‘get_called_class’ method:
abstract class dbObject
<
const TABLE_NAME = ‘undefined’ ;
public static function GetAll ()
$c = get_called_class ();
return «SELECT * FROM `» . $c :: TABLE_NAME . «`» ;
>
>
class dbPerson extends dbObject
const TABLE_NAME = ‘persons’ ;
>
class dbAdmin extends dbPerson
const TABLE_NAME = ‘admins’ ;
>
echo dbPerson :: GetAll (). «
» ; //output: «SELECT * FROM `persons`»
echo dbAdmin :: GetAll (). «
» ; //output: «SELECT * FROM `admins`»
As of PHP 5.6 you can finally define constant using math expressions, like this one:
class MyTimer const SEC_PER_DAY = 60 * 60 * 24 ;
>
Most people miss the point in declaring constants and confuse then things by trying to declare things like functions or arrays as constants. What happens next is to try things that are more complicated then necessary and sometimes lead to bad coding practices. Let me explain.
A constant is a name for a value (but it’s NOT a variable), that usually will be replaced in the code while it gets COMPILED and NOT at runtime.
So returned values from functions can’t be used, because they will return a value only at runtime.
Arrays can’t be used, because they are data structures that exist at runtime.
One main purpose of declaring a constant is usually using a value in your code, that you can replace easily in one place without looking for all the occurences. Another is, to avoid mistakes.
Think about some examples written by some before me:
1. const MY_ARR = «return array(\»A\», \»B\», \»C\», \»D\»);»;
It was said, this would declare an array that can be used with eval. WRONG! This is just a string as constant, NOT an array. Does it make sense if it would be possible to declare an array as constant? Probably not. Instead declare the values of the array as constants and make an array variable.
2. const magic_quotes = (bool)get_magic_quotes_gpc();
This can’t work, of course. And it doesn’t make sense either. The function already returns the value, there is no purpose in declaring a constant for the same thing.
3. Someone spoke about «dynamic» assignments to constants. What? There are no dynamic assignments to constants, runtime assignments work _only_ with variables. Let’s take the proposed example:
/**
* Constants that deal only with the database
*/
class DbConstant extends aClassConstant <
protected $host = ‘localhost’ ;
protected $user = ‘user’ ;
protected $password = ‘pass’ ;
protected $database = ‘db’ ;
protected $time ;
function __construct () <
$this -> time = time () + 1 ; // dynamic assignment
>
>
?>
Those aren’t constants, those are properties of the class. Something like «this->time = time()» would even totally defy the purpose of a constant. Constants are supposed to be just that, constant values, on every execution. They are not supposed to change every time a script runs or a class is instantiated.
Conclusion: Don’t try to reinvent constants as variables. If constants don’t work, just use variables. Then you don’t need to reinvent methods to achieve things for what is already there.
I think it’s useful if we draw some attention to late static binding here:
class A const MY_CONST = false ;
public function my_const_self () return self :: MY_CONST ;
>
public function my_const_static () return static:: MY_CONST ;
>
>
class B extends A const MY_CONST = true ;
>
$b = new B ();
echo $b -> my_const_self ? ‘yes’ : ‘no’ ; // output: no
echo $b -> my_const_static ? ‘yes’ : ‘no’ ; // output: yes
?>
const can also be used directly in namespaces, a feature never explicitly stated in the documentation.
const BAR = 1 ;
?>
# bar.php
require ‘foo.php’ ;
var_dump ( Foo \ BAR ); // => int(1)
?>
Hi, i would like to point out difference between self::CONST and $this::CONST with extended class.
Let us have class a:
class a <
const CONST_INT = 10 ;
public function getSelf () return self :: CONST_INT ;
>
public function getThis () return $this :: CONST_INT ;
>
>
?>
And class b (which extends a)
class b extends a const CONST_INT = 20 ;
public function getSelf () return parent :: getSelf ();
>
public function getThis () return parent :: getThis ();
>
>
?>
Both classes have same named constant CONST_INT.
When child call method in parent class, there is different output between self and $this usage.
print_r ( $b -> getSelf ()); //10
print_r ( $b -> getThis ()); //20