PHP – Constants

A constant is an identifier for any value. As the also says, that the value can’t be changed during program execution. A constant is case-sensitive by default and by convention, a constant identifiers are always uppercase. A valid constant name should start with a letter or underscore, followed by any number of letters, numbers, or underscores. Any constants name can be used anywhere in the program if needs to print the same values on various parts of the program. As a PHP constant may contain a long string value so we don’t need to write same string values again and again. You just define the constant and call it whenever you need to print the value.

How to define a PHP Constants with constant() function

To define a constant in PHP you need to use the define() function and if you want to print the value of the constant, you just need to specify the constant name only and this will print the value autometically.

constant() example

What are the main differences between constants and variables in PHP

  • There is no need to use a dollar sign ($) before any constant, instead a variable name starts with a dollar sign.
  • Constants will be defined using the define() function instead for a variable we use (=) operator to assign the value.
  • Constants values can not be chaned anywhere in the program. Once you define the program it will display the same value instead for a variable, a new value can be assigned anywhere in the program.

Magic constants in PHP

PHP provides a large number of predefined constants with the default values which are called Magic constants. The Magic constants are case-insensitive.

Following are the PHP Magic constants

  1. __LINE__
    The current line number of the file.
  2. __FILE__
    The full path and filename of the file with symlinks resolved.
  3. __DIR__
    The directory of the file.
  4. __FUNCTION__
    The function name.
  5. __CLASS__
    The class name.
  6. __TRAIT__
    The trait name.
  7. __METHOD__
    The class method name.
  8. __NAMESPACE__
    The name of the current namespace.

Leave a Reply

Your email address will not be published.