Константы в объектах

Константы также могут быть объявлены и в пределах одного класса. Отличие переменных и констант состоит в том, что при объявлении последних или при обращении к ним не используется символ $. Как и Разд. Static Keyword свойства и методы, значения констант, объявленных внутри класса, не могут быть получены через переменную, содержащую экземпляр этого класса.

Пример 19-16. Объявление и использование константы

<?php
class MyClass {
  const
constant = 'значение константы';

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

echo
MyClass::constant . "\n";

$class = new MyClass();
$class->showConstant();
/* echo $class::constant; -  такое использование недопустимо */
?>


Константы в объектах
sw at knip dot pol dot lublin dot pl
05-Jul-2006 12: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 02: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
31-Mar-2006 07: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
14-Dec-2005 08: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 06: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 :)
17-Jun-2005 09: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 01: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
24-Apr-2005 10: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 04: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 06: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
15-Dec-2004 10: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
08-Dec-2004 09: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";
}
?>

<Static KeywordАбстрактные классы>
 Last updated: Tue, 15 Nov 2005