Free guides, interview Q&As, and job responsibility breakdowns — curated by industry veterans to help you crack MNC interviews
Constants are like variables except that once they are defined, they cannot be changed. If we need to define some constant data within a class, we need to use class constants. Class constants are case-sensitive and they can be declared inside a class with the const keyword. We can also access a constant outside of a class by using the class name followed by the :: operator with the constant name.
Example:
<?php
class Namaste {
const GREETING_MSG = "Namaskaram Dosto!!";
}
echo Namaste::GREETING_MSG;
?>
We can also use the self keyword to access the constant inside the class.
Example:
<?php
class HelloWorld {
const NEW_MESSAGE = "Did I leave the Stove on?";
public function ByeWorld() {
echo self::NEW_MESSAGE;
}
}
$helloworld = new HelloWorld();
$helloworld->ByeWorld();
?>