PHP Constants

Learn about constants in PHP, their usage, and best practices.

What Are Constants in PHP?

A constant is a value that cannot be changed during the execution of a script. Once defined, a constant's value remains the same and cannot be redefined or unset.

Defining Constants

You can define a constant using the define() function. The syntax is:

<?php
define("CONSTANT_NAME", "value");
?>

Example:

<?php
define("SITE_NAME", "My Website");
echo SITE_NAME; // Outputs: My Website
?>

Constant Naming Rules

When naming constants, follow these rules:

  • Names must begin with a letter or underscore (_).
  • Names can contain letters, numbers, and underscores.
  • By convention, constant names are usually written in uppercase letters (e.g., MY_CONSTANT).

Using Constants

Once a constant is defined, you can use it anywhere in your script without a dollar sign ($):

<?php
define("PI", 3.14);
echo "Value of PI: " . PI; // Outputs: Value of PI: 3.14
?>

Magic Constants

PHP also has built-in "magic" constants that change depending on where they are used. Here are some common magic constants:

  • __LINE__: The current line number in the file.
  • __FILE__: The full path and filename of the file.
  • __DIR__: The directory of the file.
  • __CLASS__: The name of the class (when inside a class).
  • __METHOD__: The name of the method (when inside a class method).

Example:

<?php
echo "This is line: " . __LINE__; // Outputs: This is line: 14
?>

Best Practices

  • Use constants for values that do not change, such as configuration settings or fixed values.
  • Follow naming conventions to improve code readability.
  • Use uppercase letters for constant names to distinguish them from variables.

Conclusion

Constants are a powerful feature in PHP that allows you to define values that remain unchanged throughout your script. Mastering constants will help you write cleaner and more maintainable code.