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 !
Константы в объектах
Константы также могут быть объявлены и в пределах одного класса. Отличие переменных и констант состоит в том, что при объявлении последних или при обращении к ним не используется символ $. Как и Ключевое слово "static" свойства и методы, значения констант, объявленных внутри класса, не могут быть получены через переменную, содержащую экземпляр этого класса.
Пример #1 Объявление и использование константы
<?php
class MyClass {
const constant = 'значение константы';
function showConstant() {
echo self::constant . "\n";
}
}
echo MyClass::constant . "\n";
$class = new MyClass();
$class->showConstant();
/* echo $class::constant; - такое использование недопустимо */
?>
Константы в объектах
anthony dot scaife at firedupgroup dot co dot uk
10-Jul-2008 02:42
10-Jul-2008 02:42
elmar huebschmann
02-Jul-2008 06:12
02-Jul-2008 06: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-Feb-2008 03:24
13-Feb-2008 03: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
05-Oct-2007 06:19
05-Oct-2007 06: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
27-Mar-2007 10:59
27-Mar-2007 10: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
07-Dec-2006 08:58
07-Dec-2006 08: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-Nov-2006 01:32
10-Nov-2006 01: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
06-Nov-2006 06:09
06-Nov-2006 06: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-Sep-2006 04:57
24-Sep-2006 04: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
05-Jul-2006 12:14
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
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.
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
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
douglass_davis at earthlink dot net
03-Feb-2005 04:34
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.
caliban at darklock dot com
15-Dec-2004 10:55
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.
