VOOZH about

URL: https://www.geeksforgeeks.org/php/constants-and-magic-constants/

⇱ Constants and Magic Constants - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Constants and Magic Constants

Last Updated : 23 Jul, 2025

In PHP, constants and magic constants are special identifiers that hold fixed values throughout script execution. They improve code clarity, reduce repetition, and help in debugging or configuration.

This guide covers everything you need to know, from defining constants to exploring the power of magic constants for debugging and performance.

PHP Constants

PHP constants are like variables but with one key difference: their values cannot be changed once they are defined. They are used to store values that should remain consistent throughout the script, making your code more predictable.

Defining PHP Constants

You can define constants in PHP using two methods:

1. Using the define() function:


Output
3.14159

2. Using the const keyword (used for class constants):

Class Constants

Constants can also be defined in classes using the const keyword:


Output

For more details read the article - PHP Constants

PHP Magic Constants

Magic constants are predefined constants in PHP that change their value based on where they are used in the script. They help with debugging and logging information during script execution.

1. __LINE__

This constant returns the current line number in the file where it is used.


Output
2

2. __FILE__

This constant gives the full path and name of the file being executed.


Output
/home/guest/sandbox/Solution.php

3. __DIR__

Similar to __FILE__, but it returns the directory of the file being executed (without the filename).


Output
/home/guest/sandbox

4. __FUNCTION__

This constant returns the name of the function in which it is used.


Output
myFunction

5. __CLASS__

This constant gives the name of the class where it is used.


Output
MyClass

6. __METHOD__

This constant returns the name of the method where it is used.


Output
MyClass::myMethod

7. __NAMESPACE__

This constant provides the current namespace.


Output
MyNamespace

For more details read the article - PHP Magic Constants

Differences Between PHP Constants and Magic Constants

PHP constants and magic constants serve different purposes in PHP programming. While both provide fixed values, their behavior and usage vary significantly.

  • Immutability: Constants cannot be changed after definition, whereas magic constants adjust dynamically based on context.
  • Resolution Time: Regular constants are evaluated at runtime, while magic constants are determined at compile time.
  • Usage Context: Constants are user-defined, while magic constants are built into PHP and change depending on where they are used.
Comment
Article Tags:
Article Tags: