Constants in PHP OOP

Inheritance in PHP OOP
What is an Abstract Class in PHP?

In this article, we will learn about PHP constants. Constants are used to hold variables that remain constant during a program’s execution. They may be declared by using the keyword ‘const’ followed by the constant name. It should be noted that constant names in PHP are case-sensitive, however uppercase characters are preferred.

Constants in PHP

How to access the constant value within the class?

We can get the value of constant within the class using the self keyword, a scope resolution operator :: and the name of the constant. Look at the following example.

<?php
class hello {
  const MESSAGE = "Thank you for visiting PHP.org";
}

echo hellp::MESSAGE;
?>

How to access the constant value outside the class?

We can also get the value of the constant outside the class. Write the name of the class, scope resolution operator :: and the name of the constant.

<?php
class Hello {
  const MESSAGE = "Thank you for visiting PHP.org";
  public function tada() {
    echo self::MESSAGE;
  }
}

$hello= new hello();
$hello->tada();
?>

The official reference to the PHP operators.

Inheritance in PHP OOP
What is an Abstract Class in PHP?

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top