Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Constants

PHP – Class Constants

Class constants are useful for defining fixed values within a class.

A class constant is declared inside a class using the const keyword.

Once declared, a constant’s value cannot be changed.

Class constants are case-sensitive, but it is recommended to use uppercase letters for naming them.

You can access a constant from outside the class using the class name, the scope resolution operator (::), and the constant name, as shown here:

Example

<?php
class Goodbye {
  const LEAVING_MESSAGE = “Thank you for visiting W3Schools.com!”;
}

echo Goodbye::LEAVING_MESSAGE;
?>

Alternatively, you can access a constant from within the class using the self keyword, followed by the scope resolution operator (::) and the constant name, as shown here:

Example

<?php
class Goodbye {
  const LEAVING_MESSAGE = “Thank you for visiting W3Schools.com!”;
  public function byebye() {
    echo self::LEAVING_MESSAGE;
  }
}

$goodbye = new Goodbye();
$goodbye->byebye();
?>