Current Location: Home> Latest Articles> PHP Function to Retrieve Class Constant Names Explained

PHP Function to Retrieve Class Constant Names Explained

M66 2025-10-25

How PHP Function Returns Class Constant Names

PHP offers the get_class_constant() function, which allows you to easily retrieve the name of a constant from a specified class. This function accepts either a class name or a class instance, along with the name of the constant you want to retrieve.

Function Syntax

string get_class_constant(object|string $class, string $constant_name)

Parameter explanation:

  • $class: The class name or an instance of the class.
  • $constant_name: The name of the constant to return.

Usage Example

Here is a simple example showing how to use the get_class_constant() function:

class MyClass
{
    const MY_CONSTANT = 'My constant value';
}

$constant_name = get_class_constant('MyClass', 'MY_CONSTANT');

echo $constant_name; // Output: MY_CONSTANT

Notes

If the specified constant does not exist, or if $class is not a valid class name, get_class_constant() will return null.

Using this method, you can easily retrieve class constant names in PHP, which is useful for dynamically handling constants in development.