Class constant in PHP, is a constant declared inside class which value cannot be changed once assigned.
- const keyword is used to declare class constant.
- $ symbol is not used before const variable.
- Class constant variable name must be in uppercase as per naming convention.
- Class constant variable names are case-sensitive.
Syntax
<?php
class classname{
const variable_name = value;
}
?>
Example
<?php
class myClass{
const MAX_SPEED = 200;
}
?>
Access class constants
To access or use a class constant, scope resolution operator :: (double colon without space) is used with class name.
<?php
class myClass{
const MAX_SPEED = 200;
}
// Accessing class constant
echo myClass::MAX_SPEED;
?>
Inside class function
PHP allows to use $this or self to access a class constant inside class methods.
<?php
class myClass{
const MAX_SPEED = 200;
public function getSpeed(){
// With $this
echo $this::MAX_SPEED;
// With self
echo self::MAX_SPEED;
}
}
$obj = new myClass();
$obj->getSpeed();
?>