PHP OOP-Class Constants

Constants are bits of data saved in the computer’s memory that can not be modified once they have been assigned.

Constants declared within classes are known as class constants.

Declaring Class Constants

A class constant is declared with the const keyword. Class constant must be declared inside class.

Note: Class constants are case-sensitive. It is preferred that the constants be named entirely in uppercase characters.

Syntax:

<?php
class Helo {
	const MSG = 'Hello World';
}

Accessing Class Constants

Class constants can be accessed in two ways.

  1. Accessing Constant Inside Class
  2. Accessing Constant Outside Class
1.Accessing Constant Inside Class:

We can use the self keyword followed by the scope resolution operator (::) followed by the constant name to access a constant from within the class, as shown here:

<?php
class Helo {
  const MSG = "Welcome to Tutorials Art";
  public function greet() {
    echo self::MSG;
  }
}

$helo = new Helo();
$helo->greet();
?>
2.Accessing Constant Outside Class:

We can use the class name followed by the scope resolution operator (::) followed by the constant name to access a constant from outside the class, as shown here:

<?php
class Helo {
  const MESSAGE = "Welcome to Tutorials Art";
}

echo Helo::MESSAGE;
?>

When you need to declare some constant data (that doesn’t change) within a class, class constants come in handy.