PHP Constants

PHP constants are used to store values that cannot be changed during the execution of a script.

They are similar to variables, but unlike variables, the value of a constant cannot be modified after it is set.

Constants are defined using the define() function and can be used throughout the entire script.

Syntax

The syntax for defining a constant in PHP is as follows:

define(name, value, case-insensitive)
  • The name parameter is the name of the constant.
  • The value parameter is the value that the constant will hold.
  • The case-insensitive parameter is an optional parameter that specifies whether the constant name should be case-sensitive or case-insensitive. The default value is false, meaning that the constant name is case-sensitive.

Example:

define("PI", 3.14);

In this example, we define a constant named PI with a value of 3.14. Now, we can use the constant anywhere in the script like a variable.

echo PI;

Constant Arrays

PHP constants can also be arrays. They are defined the same way as regular constants, but the value passed in must be an array.

define("FRUITS", array("Apple", "Banana", "Orange"));

In this example, we define a constant named FRUITS with an array value. We can access the elements of the array using the constant name and the array index.

echo FRUITS[1];

Predefined Constants

PHP has a number of predefined constants that are available throughout the entire script. These constants have special meanings and are used for various purposes such as debugging, file paths, and more.

For example, the FILE constant returns the current file name and LINE returns the current line number.

echo "This is line " . __LINE__ . " in file " . __FILE__;

Magic Constants

PHP has a set of predefined constants called “magic constants” that are automatically set by PHP depending on the context of the code.

These constants start and end with two underscores __. Some examples include CLASSFUNCTION, and METHOD.

For example, CLASS returns the name of the current class and FUNCTION returns the name of the current function.

class MyClass {
  public function myFunction() {
    echo "Class name: " . __CLASS__ . "<br>";
    echo "Function name: " . __FUNCTION__;
  }
}

Conclusion

PHP constants are a great way to store values that will not change during the execution of a script. They can be defined using the define() function and can be used throughout the entire script, similar to variables.

Constants can also be arrays and PHP also has predefined and magic constants that can be used for various purposes. Constants are a powerful tool that can help make your code more organized and easier to maintain.

Related Posts: