PHP const Keyword

In PHP, the const keyword is used to define constants. Constants are similar to variables, but once they are defined, they cannot be changed or undefined.

Syntax

const CONSTANT_NAME = value;
  • Constants are automatically global across the entire script.

  • Constant names must follow the same naming rules as variables (start with a letter or underscore).

  • Constants are typically written in uppercase by convention.


Example

class MyClass { const VERSION = "1.0"; public function showVersion() { echo self::VERSION; } } $obj = new MyClass(); $obj->showVersion(); // Outputs: 1.0

Key Points

  • const is used for defining class constants or global constants.

  • Constants defined with const are resolved at compile time.

  • For defining constants outside of a class, you can also use the define() function (more dynamic).

define("SITE_NAME", "My Website"); // alternative way (older style)