Skip to content

const

The PHP "const" Keyword: A Comprehensive Guide

As a PHP developer, you may have used constants to define values that remain unchanged in your application. The const keyword is a fundamental building block of PHP programming, allowing you to define constants that are evaluated at compile time. In this guide, we will explore the syntax and usage of the const keyword in depth, and provide plenty of examples to help you master this important PHP feature.

Syntax

The const keyword is used to define a constant in PHP. Here is the basic syntax:

The PHP syntax of CONST

php
const NAME = value;

In this example, const defines a constant named NAME with the value value.

Examples

Let's look at some practical examples of how the const keyword can be used:

Examples of PHP const

php
<?php

// Example 1
class Circle
{
  const PI = 3.14;
  public $radius;

  public function __construct($radius)
  {
    $this->radius = $radius;
  }

  public function getArea()
  {
    return self::PI * $this->radius * $this->radius;
  }
}

$myCircle = new Circle(5);
echo "Area of circle: " . $myCircle->getArea() . PHP_EOL;

// Output: Area of circle: 78.5

// Example 2
const MY_NAME = "John";
echo "My name is " . MY_NAME;

// Output: My name is John

In these examples, we use the const keyword to define constants and reference them in different scopes.

Benefits

Using the const keyword has several benefits, including:

  • Improved code readability: Constants provide a clear and concise way to define values that remain unchanged.
  • Improved code maintenance: Constants make it easier to update values throughout your code by changing them in one place.
  • Improved code security: Constants prevent accidental changes to important values by making them read-only.

Conclusion

In conclusion, the const keyword is a powerful tool for PHP developers, allowing them to define constants and reference them efficiently. We hope this guide has been helpful, and we wish you the best of luck as you continue to develop your PHP skills.

Practice

In PHP, which of the following statements are true about constants?

Do you find this helpful?

Dual-run preview — compare with live Symfony routes.