Constants in PHP OOP

C

In this article, we will learn constants in PHP.

What are constants in PHP?

  • Constants are used to store some value that remains unchanged during the execution of the program.
  • We can declare constant using constant keyword followed by the name of the constant.
  • The name of constant is case-sensitive, however, it is recommended in PHP to name the constant in upper-case letters.
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 constant outside the class. Write the name of the class, 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";
  public function tada() {
    echo self::MESSAGE;
  }
}

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

The official reference to the PHP operators.

Add comment

Tutor Network

Learn PHP from A to Z