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. Like static members, constant values cannot be accessed from an instance of the object (using $object::constant).

例子 19-15. Defining and using a constant

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

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

echo
MyClass::constant . "\n";

$class = new MyClass();
$class->showConstant();
// echo $class::constant;  is not allowed
?>

add a note add a note User Contributed Notes
webmaster at chaosonline dot de
24-Sep-2006 07:57
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;
}
?>
sw at knip dot pol dot lublin dot pl
06-Jul-2006 03:14
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

}

?>
31-May-2006 05:03
In addition to what "tobias_demuth at web dot de" wrote:

Assigning the return value of a function to a constant does not work. Thus you may assign the return value of a function to a global constant defintion using "define()" and assign this global constant to the class constant.

The following example works as expected.

<?php

define
("MYTIME", time());

class
test {
     const
time = MYTIME;
}

print
test::time;

?>

Will output the current timestamp. Whatsoever: IMHO this is "bad style" and so I suggest NOT to use this as "workaround".
awbacker at gmail dot com
01-Apr-2006 11:15
"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"

I do see this as an omission.  They are not only access modifiers, but they limit visibility as well.  As it is, I can not make a constant that is private to my class, which I see as a problem.  I would settle for multiple modifiers like private const $var = 'me'; but that is not allowed either.
spiritus.canis at gmail dot com
15-Dec-2005 12:12
RE: mail at erwindoornbos dot nl

Sure, that'll work, but you'll have the same constant defined for your entire application.  Using class constants allows you to re-use the name of a constant while 1) holding a different value in different classes, and 2) giving you the ability to reference them from a static context.
mail at erwindoornbos dot nl
12-Dec-2005 10:21
<?php

define
('SOMETHING', 'Foo bar');

class
something
{
   function
getsomething()
   {
       echo
SOMETHING;
   }
}

$class = new something();
$class->getsomething();

?>

Works for me! This prints "Foo bar" without any warnings :)
18-Jun-2005 12:29
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
esad at 25novembar dot com
25-Apr-2005 04:03
Refering to caliban at darklock dot com's article:

The whole idea of visibility is implementing the concept of data hiding and encapsulation. This means exposing as little as possible of the class variables/methods, in order to maintain loose coupling. If you reference all your variables in your class directly, you've probably missed the point of OOP.

If the variable visibility is set to private it shouldn't be readable outside the class (performing tricks to read it is pointless, if you want to read something, make it public, it's your code). This is not used to obfuscate/hide a variable from someone but to enforce good coding practice of maintaining the loose coupling between objects.

http://c2.com/cgi/wiki?CouplingAndCohesion
tobias_demuth at web dot de
25-Apr-2005 01:39
Please note, that it is not possible to initialize an object's constant with a not-constant value. Something like this won't work:

<?php

class Testing {
     const
TIME = time();

    
// Some useful code
}

echo
Testing::TIME;

?>

It will break with: Parse error: syntax error, unexpected '(', expecting ',' or ';' in path/to/file on line anylinenumber

Hope this will help somebody...
douglass_davis at earthlink dot net
03-Feb-2005 08:34
Re: caliban at darklock dot com

most people are not going to do all of this:

<?php
  
if(isset($y["@$classname@$b"]))
       echo
"\"$b\" is private: {$y["@$classname@$b"]}<br/>";
?>

to read an object variable.

My point is: what you said is true, however access specifiers do have an effect on who gets to read the variables when you are not trying to bypass encapsulation:

<?php

class Foo
{
  
private $varname=2;
}

$obj=new Foo();
echo
$obj->varname// accessing in the usual way doesn't work
?>

So: const gives you a constant that is public in terms of reading them the usual way.  A private const would mean you could not read the variable using the 2nd method above.  Not to say it's an "omission in PHP," but, realize that there would be some value added in allowing consts to be made private.
pcarmody at c-spanarchives dot org
18-Jan-2005 10:54
It should be noted that you cannot use the return from a function to assign a value to a class constant:

<?php
class MyClass {
  const
good = "blah";
  const
bad = str("blah", 0, 3);  // causes a parse error
}
?>
caliban at darklock dot com
16-Dec-2004 02:55
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.
pezskwerl at gmail dot com
09-Dec-2004 01:02
Unlike static members, constants always have public visibility, so trying to set a constant's visibility won't work, such as in this example:

<?php
class MyClass {

    
protected static $nonConstant = "this will work";
    
protected const constant = "this won't work";
}
?>