Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
oop
class
communitycreator

What are PHP OOP class constants?

Saad Akbar

Overview

The word constant emphasizes that something is unchangeable. Class constants can be helpful to declare some constant data within a class. Using the const keyword enables us to communicate a constant in a class.

A constant can be accessed outside the class by writing the class name, the scope resolution operator:: and then the constant's name.

Example

<?php
class Description {
  const DESCRIPTION_MESSAGE = "Study PHP Class Constants from Educative!";
  
}

echo Description::DESCRIPTION_MESSAGE;
?>
Implementing constants inside class

Explanation

  • Lines 2–5: We declare a class named Description and a constant named DESCRIPTION_MESSAGE which holds a specific message.
  • Line 7: We print the constant by accessing it from outside the class Description.

We can access a constant within a class through the self keyword, which is followed by the scope resolution operator ::, and then the constant name.

Example

<?php
class Description {
  const DESCRIPTON_MESSAGE = "Thank you for visiting W3Schools.com!";
  public function CallInsideClass() {
    echo self::DESCRIPTON_MESSAGE;
  }
}

$d1 = new Description();
$d1->CallInsideClass();
?>
Accessing a constant within the class

Explanation

  • Lines 2–3: We declare a class named Description and a constant named DESCRIPTION_MESSAGE which holds a specific message.
  • Lines 4–5: We call a public function CallInsideClass() . This function prints the class constant. As it is a public function, we can call it from outside the class.
  • Lines 9–10: We create a new class object. This object then calls the public class function CallInsideClass().

RELATED TAGS

php
oop
class
communitycreator
RELATED COURSES

View all Courses

Keep Exploring