dismiss Step into the future! Click here to switch to the beta php.net site
downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | conferences | my php.net

search for in the

Autoloading Classes> <Properties
[edit] Last updated: Fri, 28 Jun 2013

view this page in

Class Constants

It is possible to define constant values on a per-class basis remaining the same and unchangeable. Constants differ from normal variables in that you don't use the $ symbol to declare or use them.

The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call.

It's also possible for interfaces to have constants. Look at the interface documentation for examples.

As of PHP 5.3.0, it's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self, parent and static).

Example #1 Defining and using a constant

<?php
class MyClass
{
    const 
constant 'constant value';

    function 
showConstant() {
        echo  
self::constant "\n";
    }
}

echo 
MyClass::constant "\n";

$classname "MyClass";
echo 
$classname::constant "\n"// As of PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo 
$class::constant."\n"// As of PHP 5.3.0
?>

Example #2 Static data example

<?php
class foo {
    
// As of PHP 5.3.0
    
const bar = <<<'EOT'
bar
EOT;
}
?>

Unlike heredocs, nowdocs can be used in any static data context.

Note:

Nowdoc support was added in PHP 5.3.0.



Autoloading Classes> <Properties
[edit] Last updated: Fri, 28 Jun 2013
 
add a note add a note User Contributed Notes Class Constants - [18 notes]
up
1
Joshua Dickerson
1 month ago
Class constants are allocated per instance of the class. If you create a class with 100 constants, each with 100 bytes, and 100 instances of that class, you will use 1 million bytes. Obviously that is a fringe case but remember that when you are creating constants that you might not need in every instance.
up
12
ryan at derokorian dot com
1 year ago
It may seem obvious, but class constants are always publicly visible. They cannot be made private or protected. I do not see it state that in the docs anywhere.
up
10
tmp dot 4 dot longoria at gmail dot com
2 years ago
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:
<?php
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()."<br>";//output: "SELECT * FROM `persons`"
echo dbAdmin::GetAll()."<br>";//output: "SELECT * FROM `admins`"

?>
up
7
anonymous
2 years ago
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:

<?php
/**
 * 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.
up
1
jakub dot lopuszanski at nasza-klasa dot pl
2 years ago
Suprisingly consts are lazy bound even though you use self instead of static:
<?php
class A{
  const
X=1;
  const
Y=self::X;
}
class
B extends A{
  const
X=1.0;
}
var_dump(B::Y); // float(1.0)
?>
up
1
riku at helloit dot fi
5 years ago
pre 5.3 can refer a class using variable and get constants with:

<?php
function get_class_const($class, $const){
  return
constant(sprintf('%s::%s', $class, $const));
}

class
Foo{
  const
BAR = 'foobar';
}

$class = 'Foo';

echo
get_class_const($class, 'BAR');
//'foobar'
?>
up
1
wbcarts at juno dot com
4 years ago
Use CONST to set UPPER and LOWER LIMITS

If you have code that accepts user input or you just need to make sure input is acceptable, you can use constants to set upper and lower limits. Note: a static function that enforces your limits is highly recommended... sniff the clamp() function below for a taste.

<?php

class Dimension
{
  const
MIN = 0, MAX = 800;

  public
$width, $height;

  public function
__construct($w = 0, $h = 0){
   
$this->width  = self::clamp($w);
   
$this->height = self::clamp($h);
  }

  public function
__toString(){
    return
"Dimension [width=$this->width, height=$this->height]";
  }

  protected static function
clamp($value){
    if(
$value < self::MIN) $value = self::MIN;
    if(
$value > self::MAX) $value = self::MAX;
    return
$value;
  }
}

echo (new
Dimension()) . '<br>';
echo (new
Dimension(1500, 97)) . '<br>';
echo (new
Dimension(14, -20)) . '<br>';
echo (new
Dimension(240, 80)) . '<br>';

?>

- - - - - - - -
 Dimension [width=0, height=0] - default size
 Dimension [width=800, height=97] - width has been clamped to MAX
 Dimension [width=14, height=0] - height has been clamped to MIN
 Dimension [width=240, height=80] - width and height unchanged
- - - - - - - -

Setting upper and lower limits on your classes also help your objects make sense. For example, it is not possible for the width or height of a Dimension to be negative. It is up to you to keep phoney input from corrupting your objects, and to avoid potential errors and exceptions in other parts of your code.
up
0
Anonymous
3 years ago
Note that since constants are tied to the class definition, they are static by definition and cannot be accessed using the -> operator.

A side effect of this is that it's entirely possible for a class constant to have the same name as a property (static or object):

<?php
class Foo
{
  const
foo = 'bar';
  public
$foo = 'foobar';

  const
bar = 'foo';
  static
$bar = 'foobar';
}

var_dump(foo::$bar); // static property
var_dump(foo::bar);  // class constant

$bar = new Foo();
var_dump($bar->foo); // object property
var_dump(bar::foo); // class constant
?>
up
0
cwreace at yahoo dot com
4 years ago
A useful technique I've found is to use interfaces for package- or application-wide constants, making it easy to incorporate them into any classes that need access to them:

<?php
interface AppConstants
{
   const
FOOBAR = 'Hello, World.';
}

class
Example implements AppConstants
{
   public function
test()
   {
      echo
self::FOOBAR;
   }
}

$obj = new Example();
$obj->test();  // outputs "Hello, world."
?>

I realize the same could be done simply by defining the constant in a class and accessing it via "class_name::const_name", but I find this a little nicer in that the class declaration makes it immediately obvious that you accessing values from the implemented interface.
up
0
webmaster at chaosonline dot de
6 years ago
Since constants of a child class are not accessible from the parent class via self::CONST and there is no special keyword to access the constant (like this::CONST), i use private static variables and these two methods to make them read-only accessible from object's parent/child classes as well as statically from outside:

<?php
class b extends a {
    private static
$CONST = 'any value';

    public static function
getConstFromOutside($const) {
        return
self::$$const;
    }

    protected function
getConst($const) {
        return
self::$$const;
    }
}
?>

With those methods in the child class, you are now able to read the variables from the parent or child class:

<?php
class a {
    private function
readConst() {
        return
$this->getConst('CONST');
    }

    abstract public static function
getConstFromOutside($const);
    abstract protected function
getConst($const);
}
?>

From outside of the object:

<?php
echo b::getConstFromOutside('CONST');
?>

You maybe want to put the methods into an interface.

However, class b's attribute $CONST is not a constant, so it is changeable by methods inside of class b, but it works for me and in my opinion, it is better than using real constants and accessing them by calling with eval:

<?php
protected function getConst($const) {
    eval(
'$value = '.get_class($this).'::'.$const.';');
    return
$value;
}
?>
up
0
caliban at darklock dot com
8 years ago
Lest anyone think this is somehow an omission in PHP, there is simply no point to having a protected or private constant. Access specifiers identify who has the right to *change* members, not who has the right to read them:

<?php
// define a test class
class Test
{
    public static
$open=2;
    protected static
$var=1;
    private static
$secret=3;
}

$classname="Test";

// reflect class information
$x=new ReflectionClass($classname);
$y=array();
foreach(
$x->GetStaticProperties() as $k=>$v)
   
$y[str_replace(chr(0),"@",$k)]=$v;

// define the variables to search for
$a=array("open","var","secret","nothing");
foreach(
$a as $b)
{
    if(isset(
$y["$b"]))
        echo
"\"$b\" is public: {$y["$b"]}<br/>";
    elseif(isset(
$y["@*@$b"]))
        echo
"\"$b\" is protected: {$y["@*@$b"]}<br/>";
    elseif(isset(
$y["@$classname@$b"]))
        echo
"\"$b\" is private: {$y["@$classname@$b"]}<br/>";
    else
        echo
"\"$b\" is not a static member of $classname<br/>";
}
?>

As you can see from the results of this code, the protected and private static members of Test are still visible if you know where to look. The protection and privacy are applicable only on writing, not reading -- and since nobody can write to a constant at all, assigning an access specifier to it is just redundant.
up
-1
elmar huebschmann
5 years ago
The major problem of constants is for me, you cant use them for binary flags.

<?php
class constant {

    const
MODE_FLAG_1 = 1;
    const
MODE_FLAG_2 = 2;
    const
MODE_FLAG_3 = 4;

    const
DEFAULT_MODE = self::FLAG_1 | self::FLAG_2

   
private function foo ($mode=self::DEFAULT_MODE) {
       
// some operations
   
}
}
?>

This code will not work because constants can't be an calculation result. You could use

<?php
   
const DEFAULT_MODE = 3;
?>

instead, but we use flags to be value indipendent. So you would miss target with it. Only way is to use defines like ever before.
up
-1
nrg1981 {AT} hotmail {DOT} com
5 years ago
If you have a class which defines a constant which may be overridden in child definitions, here are two methods how the parent can access that constant:

<?php
class Weather
{
    const
danger = 'parent';

    static function
getDanger($class)
    {
       
// Code to return the danger field from the given class name
   
}

}

class
Rain extends Weather
{
    const
danger = 'child';
}
?>

The two options to place in the parent accessor are:

        eval('$danger = ' . $class . '::danger;');
       
or:

        $danger = constant($class . '::danger');

I prefer the last option, but they both seem to work.

So, why might this be useful?   Well, in my case I have a page class which contains various common functions for all pages and specific page classes extend this parent class.   The parent class has a static method which takes an argument (class name) and returns a new instantiation of the class.  

Each child class has a constant which defines the access level the user must have in order to view the page.   The parent must check this variable before creating and returning an instance of the child - the problem is that the class name is a variable and $class::danger will treat $class as an object.
up
-1
moechofe
6 months ago
Using "const" in the global context works:

<?php
const FOO = 'bar';
var_dump(FOO);
?>
up
-1
michikono at symbol gmail dot com
6 years ago
In realizing it is impossible to create dynamic constants, I opted for a "read only" constants class.

<?php
abstract class aClassConstant {   

   
/**
     * Setting is not permitted.
     *
     * @param    string    constant name
     * @param    mixed    new value
     * @return    void
     * @throws    Exception
     */
   
final function __set($member, $value) {
        throw new
Exception('You cannot set a constant.');
    }
   
   
/**
     * Get the value of the constant
     *
     * @param    string    constant name
     * @return    void
     */
   
final function __get($member) {
        return
$this->$member;
    }
}
?>

The class would be extended by another class that would compartmentalize the purpose of the constants. Thus, for example, you would extend the class with a DbConstant class for managing database related constants, that might look like this:

<?php
/**
 * 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;
   
   
/**
     * Constructor. This is so fully dynamic values can be set. This can be skipped and the values can be directly assigned for non dynamic values as shown above.
     *
     * @return    void
     */
   
function __construct() {
       
$this->time = time() + 1; // dynamic assignment
   
}
}
?>

You would use the class like thus:

<?php
$dbConstant
= new DbConstant();
echo
$dbConstant->host;
?>

The following would cause an exception:

<?php
$dbConstant
= new DbConstant();
$dbConstant->host = '127.0.0.1'; // EXCEPTION
?>

It's not pretty, nor ideal, but at least you don't pollute the global name space with long winded global names and it is relatively elegant.

Variables must be *protected*, not public. Public variables will bypass the __get and __set methods!! This class is, by design, not meant to be extended much further than one level, as it is really meant to only contain constants. By keeping the constant definition class seperate from the rest of your classes (if you are calling this from a class), you minimize the possibility of accidental variable assignment.

Managing this instance may be a slight pain that requires either caching a copy of the instance in a class variable, or using the factory pattern. Unfortunately, static methods can't detect the correct class name when the parent name is used during the call (e.g., DbConstant::instance()). Thus there is no elegant, inheriting solution to that problem. Thus, it is easier to simply manage a single instance that is declared using conventional notation (e.g., new DbConstant...).

- Michi Kono
up
-4
Anonymous
8 years ago
It's important to note that constants cannot be overridden by an extended class, if you with to use them in virtual functions.  For example :

<?php
class abc
{
    const
avar = "abc's";
    function
show()
    {
        echo
self::avar . "\r\n";
    }
};

class
def extends abc
{
    const
avar = "def's";
    function
showmore ()
    {
        echo
self::avar . "\r\n";
       
$this->show();
    }
};

$bob = new def();
$bob->showmore();
?>

Will display:
def's
abc's

However, if you use variables instead the output is different, such as:

<?php
class abc
{
    protected
$avar = "abc's";
    function
show()
    {
        echo
$this->avar . "\r\n";
    }
};

class
def extends abc
{
    protected
$avar = "def's";
    function
showmore ()
    {
        echo
$this->avar . "\r\n";
       
$this->show();
    }
};

$bob = new def();
$bob->showmore();
?>

Will output:
def's
def's
up
-3
sw at knip dot pol dot lublin dot pl
6 years ago
It might be obvious,
but I noticed that you can't define an array as a class constant.

Insteed you can define AND initialize an static array variable:

<?php

class AClass {

    const
an_array = Array (1,2,3,4);  
     
//this WILL NOT work
      // and will throw Fatal Error:
      //Fatal error: Arrays are not allowed in class constants in...

   
public static $an_array = Array (1,2,3,4);
   
//this WILL work
    //however, you have no guarantee that it will not be modified outside your class

}

?>
up
-2
dexen dot devries at gmail dot com
2 years ago
Summary: use ReflectionObject to access class const in PHP older than 5.3.

In versions <= 5.2 you can't use the $object::constMember syntax. Accessing via class name or the `self' operator doesn't resolve the right class in case of inheritance (for the C++ folks, it behaves like a NON-virtual method). The only working (if ugly) solution to access seems to be to use the Reflection extension:

<?php

class Foo {
    const
a = 7;
    const
x = 99;
}

class
Bar extends Foo {
    const
a = 42; /* overrides the `a = 7' in base class */
}

$b = new Bar();
$r = new ReflectionObject($b);
echo
$r->getConstant('a');  # prints `42' from the Bar class
echo "\n";
echo
$r->getConstant('x');  # prints `99' inherited from the Foo class

?>

 
show source | credits | stats | sitemap | contact | advertising | mirror sites