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 default visibility of class constants is public.

The value must be a constant expression, not (for example) a variable, a
property, or a function call.

User Contributed Notes 21 notes

it's possible to declare constant in base class, and override it in child, and access to correct value of the const from the static method is possible by 'get_called_class' method:<?phpabstract class dbObject{ const TABLE_NAME='undefined';

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:

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.

Re: "The value must be a constant expression, not (for example) a variable, a property, a result of a mathematical operation, or a function call."

I dare say that "a mathematical operation" can indeed be a constant expression. I was quite surprised by this limitation; you cannot, for example do something like:

const LIMITMB = 20;const LIMITB = LIMITMB * 1024 * 1024;

It is very common to be able to express something like that in other languages, like C with #defines, where changing one definition has a cascading effect on others without having to pre-calculate hard-coded numbers all over the place. So beware, you might be better off using a private static or global contstant definition if you need to do anything more sophisticated than a name=primitive value pair.

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.

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.

Square or curly bracket syntax can normally be used to access a single byte (character) within a string. For example: $mystring[5]. However, please note that (for some reason) this syntax is not accepted for string class constants (at least, not in PHP 5.5.12).For example, the following code gives "PHP Parse error: syntax error, unexpected '[' in php shell code on line 6".<?phpclass SomeClass{ const SOME_STRING = '0123456790'; public static function ATest() { return self::SOME_STRING[0]; }}?>It looks like you have to use a variable/class member instead.

The usual comma-separated syntax can be used to declare several constants:

class STATE { const INIT=0, NAME_SEEN=1, ADDR_SEEN=2; }

This shows the declaration of a set of enumeration literals suitable for use in a finite state machine loop. Reference such an enum by using syntax such as "STATE::INIT". Its actual type in this case will be integer.

While I wouldn't use this in production, it came in very handy in my development environment where my directory locations were changing with each test version of the site being developed. Server::WEBFILEROOT was used throughout the site, so setting it automatically saved me a lot of time.