PHP Class Constants: Tutorial with Code Examples (2023)

Last Updated on

CraftyTechie is reader-supported. When you buy through links on our site, we may earn an affiliate commission.

What is a PHP Class Constant?

PHP class constant is a value defined within a class and cannot be changed during the execution of the script. They are similar to variables, but unlike variables, their value remains constant throughout the script execution.

php class constant

In object-oriented programming, class constants are used to define data that belongs to a class rather than a specific instance of a class. They offer several advantages, such as better code readability and centralized data management.

PHP Class Constant Code Example

<?php


class Math {
    public const PI = 3.14159265359;
   
    public static function areaOfCircle($radius) {
      return self::PI * $radius * $radius;
    }
   
    public static function circumferenceOfCircle($radius) {
      return 2 * self::PI * $radius;
    }
}
   
echo Math::areaOfCircle(5); // Output: 78.539816339744
echo Math::circumferenceOfCircle(5); // Output: 31.4159265358979


?>

Article Highlights

  • Class constants are immutable values that are associated with a specific class in PHP.
  • Class constants are declared using the const keyword and can be accessed using the self keyword or the class name.
  • They should follow naming conventions and have an appropriate visibility modifier based on the needs of the class.
  • Class constants can be used as expressions in mathematical or string concatenation operations.
  • Private constants provide a way to store sensitive data only accessible within the class, while public constants can be used as part of a class’s public API.
  • Class constants offer advantages over global variables, such as better code organization, encapsulation, and data integrity.

Disclaimer: Object-Oriented Programming

The class constant is a sub-topic in Object Oriented Programming (OOP). We have already used the terms – class & instance. You may read more OOP terms, and if you are not sure about them, then consider reading Object-Oriented PHP Programming Tutorial at FuelingPHP.

This article overviews the fundamentals of OOP and will provide you with solid ground. 

Table of Contents

Advantages of Class Constants

Using class constants can have several advantages, including:

  • Improved code readability: Using constants instead of hardcoded values makes the code easier to read and understand.
  • Centralized data: By defining a constant within a class, it is easier to manage data in a centralized location.
  • Prevent data modification: Constants cannot be modified during the script execution, so they provide a certain level of security against data modification.

Syntax and Rules for Declaring Constants

The syntax for declaring a class constant is similar to that of a class property but with the const keyword before the constant name. The following are the rules for declaring constants:

  • A constant name must start with a letter or underscore.
  • A constant name can contain letters, numbers, and underscores.
  • A constant name cannot start with a number.
  • A constant name is case-sensitive.

How to Declare a Class Constant

To declare a class constant in PHP, use the const keyword followed by the constant name and value. Here’s an example:

<?php


class MyClass {
  const MY_CONST = 10;
}


?>

In the above example, MY_CONST is the name of the constant, and 10 is the value of the constant. Once a constant is defined, it can be accessed throughout the class.

Naming Conventions for Constants

It is common to use uppercase letters and underscores to separate words in a constant name. This is known as the “snake case” naming convention. For example:

<?php


class MyClass {
    const MY_CONSTANT = 'some value';
}
 
?>

Visibility of Class Constants

In PHP, class constants can have a visibility modifier just like class properties and methods. There are three visibility modifiers: 

  • public: Accessible from anywhere in the code.
  • protected: Accessible within the class and any child classes.
  • private: Only accessible within the class it is defined in.

Default Visibility of a Class Constant

If a visibility modifier is not specified, then the constant is considered public by default. Here’s an example:

<?php


class MyClass {
    public const MY_CONST = 10;
}


echo MyClass::MY_CONST; //Output: 10


?>

In the above example, MY_CONST is a public constant that is accessible anywhere in the code.

Using Constants as Expressions

Class constants can be used as expressions in PHP. This means that they can be used in place of a value. Here’s an example:

<?php


class MyClass {
    const MY_CONST = 10;
   
    public function myFunction($value) {
      return $value * self::MY_CONST;
    }
}




$instance = new MyClass(); //Creates an instance of MyClass


echo $instance->myFunction(10); //Output: 100


?>

The above example uses MY_CONST as an expression in the myFunction() method.

Private Const vs Public Const

As discussed already, class constants can be private, protected, or public. By default, a constant is public. Here’s an example:

<?php


class MyClass {
    private const MY_PRIVATE_CONST = 10;


    public const MY_PUBLIC_CONST = 20;
   
}


echo MyClass::MY_PUBLIC_CONST; //Output: 10


echo MyClass::MY_PRIVATE_CONST; //Fatal error: Uncaught Error: Cannot access private constant MyClass::MY_PRIVATE_CONST


?>

private class member and is accessible outside the class.

Example of PHP Class Constants

Let’s consider a Math class that provides various mathematical functions. The class has a constant named PI, which is used in some of the class’s functions.

<?php


class Math {
    public const PI = 3.14159265359;
   
    public static function areaOfCircle($radius) {
      return self::PI * $radius * $radius;
    }
   
    public static function circumferenceOfCircle($radius) {
      return 2 * self::PI * $radius;
    }
}
   
?>

In the above example, we define a Math class with two static functions that calculate the area and circumference of a circle. Both functions use the PI constant. 

By defining PI as a constant within the Math class, we ensure that its value cannot be changed accidentally, thus avoiding potential bugs in the code.

Here’s an example of how we can use the Math class:

echo Math::areaOfCircle(5); // Output: 78.539816339744
echo Math::circumferenceOfCircle(5); // Output: 31.4159265358979

By using a class constant to store the value of PI, we can encapsulate it and protect it from modifications of any sort as all functions that depend on it. 

In addition, by using a Math class instead of global functions, we avoid polluting the global namespace with unnecessary functions, leading to naming conflicts and making the code harder to read and understand.

Important Caveats of PHP Class Constants

Static Function with Public Constant

Class constants can also be used in static functions. Here’s an example:

<?php


class MyClass {
    public const MY_CONST = 10;
   
    public static function myStaticFunction() {
      return self::MY_CONST;
    }
}
 
echo MyClass::myStaticFunction(); // Output: 10
 
   
?>

In the above example, MY_CONST is a public constant in MyClass. The myStaticFunction() function is a static function that returns the value of MY_CONST

Child Classes with Parent Classes and Private Constants

The child classes inherit constants from a parent class.

<?php


class ParentClass {
    public const MY_CONST = 10;
}
 
class ChildClass extends ParentClass {


    public const MY_PUBLIC_CONST = 20;
   
    public static function myStaticFunction() {


      return self::MY_CONST + self::MY_PUBLIC_CONST;
    }
}




echo ChildClass::myStaticFunction(); //Output: 30


?>

However, private constants defined in the parent class are not accessible in the child class. Here’s an example:

<?php


class ParentClass {
    private const MY_CONST = 10;
  }
 
  class ChildClass extends ParentClass {
    public const MY_PUBLIC_CONST = 20;
   
    public function myFunction() {
      // This will throw an error: Cannot access private const MY_CONST
      return self::MY_CONST + self::MY_PUBLIC_CONST;
    }
}


?>

In the above example, MY_CONST is a private constant in the ParentClass. It is not accessible in the ChildClass because it is private. 

Common Errors When Working With PHP Class Constant

Undefined Constant Errors

One common error when working with class constants is an undefined constant error. This can happen if you try to access an undefined constant. Here’s an example:

<?php


class MyClass {
    public const MY_CONST = 10;
}
 
echo MyClass::MY_OTHER_CONST; //Fatal error: Uncaught Error: Undefined constant MyClass::MY_OTHER_CONST


?>

In the above example, MY_OTHER_CONST is undefined, so we see an error.

Fatal Error When Re-Declaring a Constant

Another common error is a fatal error that occurs when trying to re-declare a constant. Once you define a constant, you cannot re-declare or change it during the script execution. Here’s an example:

<?php


class MyClass {
    public const MY_CONST = 10;
   
    // This will throw a fatal error: Cannot redeclare class constant
    public const MY_CONST = 20;
}
 
?>

The above example re-declares MY_CONST with a different value, and that’s why we get the error.

Fatal Error When Using a Private Constant Outside the Class

We get a fatal error if we try to access a private constant outside their class. Consider the following example:

<?php


class MyClass {
    private const MY_CONST = 10;
}
 
echo MyClass::MY_CONST; // Fatal error: Uncaught Error: Cannot access private const MyClass::MY_CONST
 
?>

The above example defines a private constant MY_CONST inside the MyClass class. When we try to access this constant from outside the class using the echo statement, we get a fatal error because private constants are not accessible from outside their class.

Avoid this error by changing the visibility of the constant to either public or protected or by accessing the constant from within the class or its child classes.

What are PHP Class Constants

In conclusion, class constants are an important feature in PHP’s OOP paradigm. They offer several advantages over using global variables, such as better code organization, encapsulation, and data integrity. By declaring a constant within a class, you ensure that its value cannot be changed accidentally, thus avoiding hard-to-debug errors.

It’s important to follow the syntax and naming conventions for declaring class constants and to choose the appropriate visibility modifier based on your needs. Public constants are accessible from anywhere in the code, protected constants are accessible within the class and any child classes, and private constants are accessible within their class.

By understanding how to use PHP class constants effectively, you can write cleaner, more maintainable code that is easier to debug and modify over time.

Did you find this article helpful?

Join the best weekly newsletter where I deliver content on building better web applications. I curate the best tips, strategies, news & resources to help you develop highly-scalable and results-driven applications.

Build Better Web Apps

I hope you're enjoying this article.

Get the best content on building better web apps delivered to you.