PHP Doku:: Klassenkonstanten - language.oop5.constants.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchSprachreferenzKlassen und ObjekteKlassenkonstanten

Ein Service von Reinhard Neidl - Webprogrammierung.

Klassen und Objekte

<<Eigenschaften

Autoloading>>

Klassenkonstanten

Es ist möglich für jede Klasse konstante Werte zu definieren, die gleich und unabänderlich bleiben. Konstanten weichen darin von normalen Variablen ab, dass man nicht das $ Symbol benutzt, um sie zu deklarieren oder zu benutzen.

Der Wert kann nur ein konstanter Ausdruck sein, keine (zum Beispiel) Variablen, Klassenmamber, Ergebnisse einer mathematischen Operation oder Funktionsaufrufe.

Ein Interface kann ebenfalls constants enthalten. Die Interface-Dokumentation enthält Beispiele dazu.

Beginnend mit PHP 5.3.0 ist es möglich eine Variable als Klassenreferenz zu nutzen. Der Variablenwert kann kein Schlüsselwort (wie self, parent oder static) sein.

Beispiel #1 Eine Konstante definieren und benutzen

<?php
class MyClass
{
    const 
constant 'Konstanter Wert';

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

echo 
MyClass::constant "\n";

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

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

echo 
$class::constant;  // Ab PHP 5.3.0
?>

Beispiel #2 Beispiel für statische Daten

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

Nowdocs können, anders als heredocs, in jedem statischen Datenkontext verwendet werden.

Hinweis:

Unterstützung von Nowdocs wurde in PHP 5.3.0 eingeführt.


25 BenutzerBeiträge:
- Beiträge aktualisieren...
jakub dot lopuszanski at nasza-klasa dot pl
14.11.2010 20:20
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)
?>
anonymous
28.09.2010 3:32
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.
John Galt
7.08.2010 22:30
A handy workaround to create a constant that contains array data using eval():

<?php
 
class MyClass
 
{
  const
MY_ARR = "return array(\"A\", \"B\", \"C\", \"D\");";
  public function
__construct()
  {
   return eval(
MY_ARR);
  }
 }

 
// Test implementation
 
$myClass = new MyClass();
 echo
"<pre>";
 
print_r($myClass);
 echo
"</pre>";
?>
narwhal dot jury at gmail dot com
4.03.2010 22:04
It's worth noting that with v5.3, the problem mentioned a few times in these notes of referencing a childs const within a parent is solved!

<?php
class MyClass {

     const
MY_CONST = "yonder";

     public function
__construct() {
         
         
$c = get_class( $this );
          echo
$c::MY_CONST;
     }
}

class
ChildClass extends MyClass {

     const
MY_CONST = "bar";
}

$x = new ChildClass(); // prints 'bar'
$y = new  MyClass(); // prints 'yonder'
?>

RJ
noone at example dot com
20.01.2010 15:24
You cannot use Arrays as constants.
Anonymous
13.11.2009 21:03
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
?>
mr dot lukes at gmail dot com
20.02.2009 5:02
How to get good constant when you extend the class?
Check this out...

<?php
class A {
    private
$a;   
    const
NAME = "AAA";
    public function
__construct() {
       
$this->a = "aaa";
    }
    public function
myName() {
       
$class = get_class($this);
        eval(
"\$a = $class::NAME;");
        return 
$a;
    }
}

class
B extends A {
    private
$a;   
    const
NAME = "BBB";
    public function
__construct() {
       
$this->a = "bbb";
    }

   
}

$b = new B();
echo
B::NAME;
echo
"\n";
echo
$b->myName();
echo
"\n";
?>

Output:
BBB
BBB
cwreace at yahoo dot com
7.10.2008 3:22
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.
wbcarts at juno dot com
12.09.2008 21:12
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.
anthony dot scaife at firedupgroup dot co dot uk
10.07.2008 11:42
I don't understand the issues you all seem to be having with class constants.

For me they are simply another method of grouping related functions and data together in a logical package, and keeping things out of global scope.

Class constants were something I felt very much missing from PHP4 (I have a background in C++).

You can use them like this

<?php

class mySql
{
    const
ERR_CONN = 'Connection attempt failed';
    const
ERR_SELECT_DB = 'Database selection attempt failed';
    const
ERR_QUERY = 'Invalid SQL query';

// ....    etc
}

?>

Later, you could then use the constants like this

<?php

$err
= $db->getErr();

echo
"<!-- DB failure : $err -->";

switch(
$err)
{
    case
mySql::ERR_CONN:    // Do this
   
case mySql::ERR_SELECT_DB:    // Do that
   
case mySql::ERR_QUERY:    // Do something else
}

?>

and if you need to find what other constants the class uses, you just find the class !
elmar huebschmann
2.07.2008 15:12
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.
riku at helloit dot fi
13.02.2008 12:24
pre 5.3 can refer a class using variable and get constants with:

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'
nrg1981 {AT} hotmail {DOT} com
5.10.2007 15:19
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.
kevin at metalaxe dot com
28.03.2007 7:59
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!
michikono at symbol gmail dot com
8.12.2006 5:58
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
kevin at metalaxe dot com
10.11.2006 22:32
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.
lucas dot s at ono dot com
7.11.2006 3:09
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!
webmaster at chaosonline dot de
24.09.2006 13: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
5.07.2006 21: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.05.2006 11: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
1.04.2006 5: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.

17.06.2005 18: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.04.2005 10: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
douglass_davis at earthlink dot net
3.02.2005 13: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.
caliban at darklock dot com
15.12.2004 19: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.



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)