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



PHP : Language Reference : Classes and Objects (PHP 5) : Class Constants

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 class member, result of a mathematical operation or a function call.

As of PHP 5.3.0, it's possible to reference the class using a variable. Keywords like self, parent or static are not allowed in dynamic class references.

Example 10.17. 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";

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

echo
$class::constant."\n";
?>


Code Examples / Notes » language.oop5.constants

pezskwerl

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";
}
?>


yarco dot w

Though they always use class to contain constants above, interface could also contains constants. See below:
<?php
interface I
{
 const A = 0x0;
 const B = 0x1;
}
print I::A;
?>
That works fine.


webmaster

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;
}
?>


esad

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


spiritus.canis

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.


douglass_davis

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.


tobias_demuth

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...


maikel

One way to access class constants from an instance is using the __get method, example:
<?php
class MyClass
{
  const MY_CONSTANT = "Constant class";
  public static function __get($name)
  {
     if(defined("self::$name"))
     {
        return constant("self::$name");
       
     }
     trigger_error ("Constant $name  isn't defined");
  }
}
$instance = new MyClass();
echo $instance->MY_CONSTANT; //it works!!
?>


caliban

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.


17-jun-2005 05: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


pcarmody

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
}
?>


sw

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
}
?>


lucas dot s

In the same way "define()" can be used to create a GLOBAL constant that can be assigned as the value of a CLASS constant (like anonymous (31-May-2006 10:03) noted a few posts back), MAGIC constants (__LINE__, __FILE__, etc.) can also be assigned to a CLASS constant :-) Note that an instance of ReflectionClass can be used to obtain the exact same info that magic constants can offer you...
<?php
class MyClass
{
const FILE_I_AM_IN = __FILE__;
}
echo MyClass::FILE_I_AM_IN;
?>
This outputs the file the class definition is located in, as expected.
Notes on the other magic constants:
__LINE__ = does output the correct line but... is of course completely useless...
__FUNCTION__ = does not output anything.
__METHOD__ = outputs the class name!


kevin

In response to anon on 31-May-2006 02:03:
If you can define a global constant based on the return of a function, please explain why you do not see it justifiable that a class constant should be able to be assigned in the same manner.
This affects ALL members of a class, not just constants and, for the sake of class constants, I see this as quite severe limitation to PHP. Take the following class for example:
<?php
class parser
{
   private $magic_quotes = false;
   public function __construct()
   {
       $this->magic_quotes = (bool)get_magic_quotes_gpc();
   }
   public my_stripslashes( $str )
   {
        if( $this->magic_quotes )
        {
            $str = stripslashes( $str );
        }
        return $str;
   }
}
?>
Wouldn't this be much cleaner and easier to impliment like this?
<?php
class parser
{
   const magic_quotes = (bool)get_magic_quotes_gpc();
   public my_stripslashes( $str )
   {
        if( self::magic_quotes_gpc )
        {
            $str = stripslashes( $str );
        }
        return $str;
   }
}
?>
In the second iteration, there isn't a need to scour through the script to find where magic_quotes is assigned a value and there is no confusion as to EXACTLY what magic_quotes is. More so, there is no worry that some silly end user will be able to change the value of magic_quotes in any of their "modifications" to your code as constants are a read only property. Personally I find this practical for script operation., but completely impossible in PHP.


michikono

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


31-may-2006 10: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".


gt

If you would like to generate a constant names dynamically, then one could use the functions defined() and constant():
class CONFIG {
 const MYCONST1 = 'Hello ';
 const MYCONST2 = 'World';
 public static function get($_name) {
   if(defined("self::$_name"))
     return constant("self::$_name");
   throw new Exception('Constant ' . $_name . ' is not defined');
 }
}
$vars = array(1,2);
try {
 foreach($vars as $const_suffix) {  
   echo CONFIG::get('MYCONST' . $const_suffix);
 }
} catch (Exception $e) {
 $msg = $e->getMessage();
 echo $msg;
}
Output will print:
Hello World


nrg1981 {at} hotmail {dot} com

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:
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.


php

I was having problems accessing my constants from an extended class in my abstract class, i.e.:
abstract class a {
public function showConst() {
echo self::foo;
}
}
class b extends a {
const foo = 'something';
}
I found a way to work around this is to switch self::foo with eval("return " . get_class($this) . "::foo;")
hope this helps someone.


kevin

gt at realvertex.com
You miss the point. Allowing dynamically assigned class constants will prevent the cluttering of global constants and allow you to even protect the accessibility of said constants to prevent conflicts. For example, the constants for class MySQL won't be directly available to the class Display. So I don't have to worry about prefixing all of my constants (which shouldn't be necessary and is just plain ugly).
Either way, class constants simply do not follow the global constant operation. You are allowed to set a global constant at any time during the script, yet class constants are only allowed to be set in the class header and are processed prior to script execution.
michikono at symbol gmail dot com:
This is an interesting solution and I think I will implement it as a temporary "solution" to the constant issue. Thank you for taking the time to post!


mail

<?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 :)


awbacker

"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.


Change Language


Follow Navioo On Twitter
Introduction
The Basics
Autoloading Objects
Constructors and Destructors
Visibility
Scope Resolution Operator (::)
Static Keyword
Class Constants
Class Abstraction
Object Interfaces
Overloading
Object Iteration
Patterns
Magic Methods
Final Keyword
Object cloning
Comparing objects
Reflection
Type Hinting
Late Static Bindings
eXTReMe Tracker