PHP 8.1 supports the final
flag on class constants.
Constants declared on PHP classes can be overridden by sub classes. Prior to PHP 8.1, the final
flag was not allowed on class constants, which would have protected class constants from being overridden by sub classes. Attempting to use the final
flag on class constants resulted in a fatal error.
In PHP 8.1 and later, the final
flag is allowed on
class/interface constants, and none of the sub classes are allowed to extend/override final
constants.
class Foo {
final public const TEST = '1';
}
class Bar extends Foo {
public const TEST = '2';
}
Fatal error: Bar::TEST cannot override final constant Foo::TEST in %s on line %d
final private const
Adding final
flag to a private
constant is not allowed because private
constants/methods/properties cannot be accessed outside the class itself.
Declaring a final private
constant results in a fatal error:
class Foo {
final private const TEST = '1';
}
Fatal error: Private constant Foo::TEST cannot be final as it is never overridden in ... on line ...
Interface constant changes
Prior to PHP 8.1, overriding interface
constants was not allowed, and resulted in a fatal error. This behavior has changed in PHP 8.1.
interface I {
const C = 16;
}
class Cl implements I{
const C = 1;
}
In the snippet above, I::C
constant is overridden by the class Cl
. Although I::C
constant is not declared final
, this was not allowed prior to PHP 8.1:
Fatal error: Cannot inherit previously-inherited or override constant C from interface I in ... on line ...
With the introduction of final
constants in PHP 8.1, classes and interfaces are allowed to override a previously-declared class, unless the constant is declared with a final
flag.
In PHP 8.1, Interfaces constants support the final
flag as well, and attempting to override results in an error, just like it does when overriding a class constant:
interface I {
final public const C = 16;
}
class Cl implements I{
const C = 1;
}
Fatal error: Cl::C cannot override final constant I::C in ... on line ...
The same also applies when an Interface extends another Interface and override a
final
constant.
Reflection API Changes
ReflectionClassConstant
class from the Reflection API has a new method isFinal
:
class ReflectionClassConstant {
// ...
public function isFinal(): bool {}
}
ReflectionClassConstant::isFinal
returns a bool
value whether a given class constant is declared final
.
class Foo {
final private const TEST = '1';
}
$reflector = new ReflectionClassConstant(Foo::class, 'TEST');
$reflector->isFinal(); // true
- Constant visibility
modifiers (
public const FOO
, private const FOO
, etc) were introduced in PHP 7.1. - PHP 8.0: Inheritance rules are not applied to
private
class methods
The final
flag behavior on private
class methods changed in PHP 8.0. Prior to PHP 8.0, overriding a final private
method was not allowed, and resulted in a fatal error. From PHP 8.0 and later, this is allowed (but only for private
methods), and
PHP emits a PHP warning.
Backwards Compatibility Impact
This is a language-level change, it is not possible to port this feature to older PHP versions. Using final
flag on PHP versions older than 8.1 causes a fatal error:
Fatal error: Cannot use 'final' as constant modifier in ... on line ...
Note that the behavior of Interfaces has changed; PHP
8.1 and later allows re-declaring a non-final Interface constant. Existing code that relied on this behavior and assumed that Interface constants will never be overridden might need to add the final
flag to the Interface constant to ensure it is not overridden in PHP 8.1 and later versions.
RFC Discussion
Implementation
It is possible to define constants on a per-class basis remaining the same and unchangeable. The default visibility of class constants is public
.
Note:
Class constants can be redefined by a child class. As of PHP 8.1.0, class constants cannot be redefined by a child class if it is defined as final.
It's also possible for interfaces to have constants
. Look at the interface documentation for examples.
It's possible to reference the class using a variable. The variable's value can not be a keyword (e.g. self
, parent
and static
).
Note that class constants are allocated once per class, and not
for each class instance.
Example #1 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";
?>
The special ::class
constant allows for fully qualified class name resolution at compile time, this is useful for namespaced classes:
Example #2 Namespaced ::class example
<?php
namespace foo {
class bar {
}
echo
bar::class; // foo\bar
}
?>
Example #3 Class constant expression
example
<?php
const ONE = 1;
class foo {
const TWO = ONE * 2;
const THREE = ONE + self::TWO;
const SENTENCE = 'The value of THREE is '.self::THREE;
}
?>
Example #4 Class constant visibility modifiers, as of PHP 7.1.0
<?php
class Foo {
public const BAR = 'bar';
private const BAZ = 'baz';
}
echo Foo::BAR, PHP_EOL;
echo Foo::BAZ, PHP_EOL;
?>
Output of the above example in PHP 7.1:
bar
Fatal error: Uncaught Error: Cannot access private const Foo::BAZ in …
Note:
As of PHP 7.1.0 visibility modifiers are allowed for class constants.
tmp dot 4 dot longoria at gmail dot com ¶
11 years ago
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:
<?php
abstract class dbObject
{
const TABLE_NAME='undefined';
public static function
GetAll()
{
$c = get_called_class();
return "SELECT * FROM `".$c::TABLE_NAME."`";
}
}class
dbPerson extends dbObject
{
const TABLE_NAME='persons';
}class
dbAdmin extends dbPerson
{
const TABLE_NAME='admins';
}echo
dbPerson::GetAll()."<br>";//output: "SELECT * FROM `persons`"
echo dbAdmin::GetAll()."<br>";//output: "SELECT * FROM `admins`"?>
kuzawinski dot marcin at gmail
dot com ¶
7 years ago
As of PHP 5.6 you can finally define constant using math expressions, like this one:
<?phpclass MyTimer {
const SEC_PER_DAY = 60 * 60 * 24;
}?>
Me happy :)
anonymous ¶
11 years ago
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.
delete dot this dot and dot dots dot gt at kani dot hu ¶
8 years ago
I think it's useful if we draw some attention to late static binding here:
<?php
class A {
const MY_CONST = false;
public function my_const_self() {
return self::MY_CONST;
}
public function my_const_static() {
return static::MY_CONST;
}
}
class
B extends A {
const MY_CONST = true;
}$b = new B();
echo $b->my_const_self ? 'yes' : 'no'; // output: no
echo $b->my_const_static ? 'yes' : 'no'; // output: yes
?>
Xiong Chiamiov ¶
8 years ago
const can also be used directly in namespaces, a feature never explicitly stated in the documentation.
<?php
# foo.php
namespace Foo;
const
BAR = 1;
?>
<?php
# bar.php
require 'foo.php';var_dump(Foo\BAR); // => int(1)
?>
jimmmy dot chief at gmail dot
com ¶
5 years ago
Hi, i would like to point out difference between self::CONST and $this::CONST with extended class.
Let us have class a:
<?php
class a {
const CONST_INT = 10;
public function
getSelf(){
return self::CONST_INT;
} public function
getThis(){
return $this::CONST_INT;
}
}
?>
And class b (which extends a)<?php
class b extends a {
const CONST_INT = 20;
public function
getSelf(){
return parent::getSelf();
} public function
getThis(){
return parent::getThis();
}
}
?>
Both classes have same named constant CONST_INT.
When child call method in parent class, there is different output between self and $this usage.<?php
$b = new b();print_r($b->getSelf()); //10
print_r($b->getThis()); //20?>
nepomuk at nepda dot de ¶
6 years
ago
[Editor's note: that is already possible as of PHP 5.6.0.]
Note, as of PHP7 it is possible to define class constants with an array.
<?php
class MyClass
{
const ABC = array('A', 'B', 'C');
const A = '1';
const B = '2';
const C = '3';
const NUMBERS = array(
self::A,
self::B,
self::C,
);
}
var_dump(MyClass::ABC);
var_dump(MyClass::NUMBERS);
// Result:
/*
array(3) {
[0]=>
string(1) "A"
[1]=>
string(1) "B"
[2]=>
string(1) "C"
}
array(3) {
[0]=>
string(1) "1"
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
*/
?>
wbcarts at juno dot com ¶
14 years ago
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.
<?phpclass 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.
Paul ¶
7 years ago
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".
<?php
class 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.
Nimja ¶
5 years ago
Note that this magic constant DOES NOT load classes. And in fact can work on classes that do not exist.
This means it does not mess with auto-loading.
<?php
$className = \Foo\Bar::class;
var_dump($className);
var_dump(class_exists($className, false));
?>
Will output:
string(7) "Foo\Bar"
bool(false)
info at stanzentech dot com ¶
7
years ago
<?php
//http://php.net/manual/en/language.oop5.constants.php
/**
* Constant name shouldn't start with $
* Constant name may lower or uppercases.
* Same constant name can be used as a property name but must start with $ symbol.
* Constant doesn't available with $this-> inside class definition.
* Constant is available with self:: inside class definition.
* Constant can't call with $this-> outside class.
* Constant is accessible with :: after "Class Name or Object".
*
*/
class MyClass
{
// Parse error: syntax error, unexpected '$CONSTANT' (T_VARIABLE), expecting identifier (T_STRING) in constant.php
//const $CONSTANT = 'constant named "CONSTANT" ';const CONSTANT = 'constant named "CONSTANT" ';
const small = 'constant named "small" ';
public
$small = 'SAME CONTSNAT NAME AS PROPERTIES.'; //Fatal error: Cannot redefine class constant MyClass::small in constant.php
// const small = 'constant named "small" ';function showConstant() {
echo self::CONSTANT . "<br>";
//echo $this->CONSTANT . "<br>"; // Notice: Undefined property: MyClass::$CONSTANT in constant.php
}
}$class = new MyClass();
$class->showConstant();//Notice: Undefined property: MyClass::$CONSTANT in constant.php
//echo $class->CONSTANT."<br>"; echo $class->small."<br>"; // SAME CONTSNAT NAME AS PROPERTIES.
?>
David Spector ¶
4 years ago
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.
Anonymous ¶
8 years ago
Noted by another is that class constants take up memory for every instance. I cannot see this functionality being accurate, so testing thusly:
class SomeClass {
const thing = 0;
const thing2 = 1;
}
$m0 = memory_get_usage();
$p0 = new SomeClass();
$p1 = new SomeClass();
$p2 = new SomeClass();
$m1 = memory_get_usage();
printf("memory %d<br />", $m1 - $m0);
The output does not change when one alters the count of constants in "SomeClass".
enrico_kaelert at kabelmail dot
com ¶
8 years ago
additional to tmp dot 4 dot longoria at gmail dot com ´s post:
quote:
it's possible to declare constant in base class, and override it in child,
/quote
Its not that we overwrite them.
Its more that each got its own:
<?php
abstract class dbObject
{
const TABLE_NAME='undefined';
}
class
dbPerson extends dbObject
{
const TABLE_NAME='persons'; public static function
getSelf()
{
return self::TABLE_NAME;
}
public static function getParent()
{
return parent::TABLE_NAME;
}
}class
dbAdmin extends dbPerson
{
const TABLE_NAME='admins'; public static function
getSelf()
{
return self::TABLE_NAME;
}
public static function getParent()
{
return parent::TABLE_NAME;
}
}echo
'<pre>
im class dbPerson{} and this is my:
self TABLE_NAME: '.dbPerson::getSelf().' // persons
parent TABLE_NAME: '.dbPerson::getParent().' // undefinedim class dbAdmin{} and this is my:
self TABLE_NAME: '
.dbAdmin::getSelf().' // admins
parent TABLE_NAME: '.dbAdmin::getParent().' // persons
';
?>
or more readable:
<?php
class ParentClass
{
const CONSTANT = 'CONST_PARENT';
}class
A extends ParentClass
{
const CONSTANT = 'CONST_A'; public static function
getSelf()
{
return self::CONSTANT;
}
public static function getParent()
{
return parent::CONSTANT;
}
}echo
'<pre>
im class A{} and this is my:
self CONSTANT: '.A::getSelf().' // CONST_A
parent CONSTANT: '.A::getParent().' // CONST_PARENT
';
?>
jaimz at vertigolabs dot org ¶
8 years
ago
I thought it would be relevant to point out that with php 5.5, you can not use self::class, static::class, or parent::class to produce a FQN. Doing so produces a PHP Parse error:
"PHP Parse error: syntax error, unexpected 'class' (T_CLASS), expecting variable (T_VARIABLE) or '$'"
It would be nice if you could do this however.
jakub dot lopuszanski at nasza-klasa dot pl ¶
11 years ago
[Editor's note: that behavior has changed as of PHP 7.0.0, though.]
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)
?>
ardv five two six at gmail dot com ¶
4 years ago
I think note "tmp dot 4 dot longoria at gmail dot com" may be some extend in this note.
<?php
abstract class dbObject
{
const TABLE_NAME='parentConst';
public static function
GetAll()
{
$c = get_called_class();
return "SELECT * FROM `".$c::TABLE_NAME."`";
}
public static function getChildConst()
{
return "SELECT * FROM `".static::TABLE_NAME."`"; // Late Static Bindings
}
public static function getParentConst()
{
return "SELECT * FROM `".self::TABLE_NAME."`";
}
}class
dbPerson extends dbObject
{
const TABLE_NAME='childPersonsConst';
}class
dbAdmin extends dbPerson
{
const TABLE_NAME='childAdminsConst';
}echo
dbPerson::GetAll()."<br>";//output: "SELECT * FROM `childPersonsConst`"
echo dbAdmin::GetAll()."<br>";//output: "SELECT * FROM `childAdminsConst`"echo dbPerson::getChildConst()."<br>";//output: "SELECT * FROM `childPersonsConst`"
echo dbAdmin::getChildConst()."<br>";//output: "SELECT * FROM `childAdminsConst`"echo dbPerson::getParentConst()."<br>";//output: "SELECT * FROM `parentConst`"
echo dbAdmin::getParentConst()."<br>";//output: "SELECT * FROM `parentConst`"
?>
dubious ¶
4 years ago
If absolutely necessary you can set class constants to variables like this:
$temp_wfr = substr(dirname(__FILE__),0,-3); // temp site root directory
$toeval = <<<TOEVAL
class Server extends Server_Base {
const LOCATION = "development";
const WEBFILEROOT = "$temp_wfr";
}
TOEVAL;
eval($toeval);
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.
The final keyword prevents child classes from overriding a method or constant by prefixing the definition with final . If the class itself is being defined final then it cannot be extended.