Course Banner


PHP Constants

What is Constant in PHP?

Unlike variable whose value changes during program execution, the constant values are fixed. We declare constant like variables but, the difference is that once its value is defined, it does not change during program execution. Yes, there are few constants called magic constants whose value can be changed.

When to use contestant?

Constants are used for storing data that doesn't require to change during program execution. If one tries to change its value or redefine same constant then it throws error. Its normally used in in setting or configuration files where database connections, website url, admin url etc are stored and remains same throughout the program.

How to define constants?

Unlike variable which we start with $ sign followed by variable name, in case of constant, we use PHP’s built-in function called 'define()' function. In this function, we pass two arguments, the first one is constant name and the second one is the value.

Constant names are normally defined in Capital Letters and accessed without $sign.

Example :

<?php
  1. define('SITEURL','http://www.tutorialrays.com');
  2. echo SITEURL; // TO DISPLAY THE COSNTSTANT VALUE
  3. ?>

In the above program you can see there is no dollar sign for defining the constant. If you try to redefine the constant, it will throw warning and the value is not overwritten. It will show the first value.

Let’s modify the code and run into browser and check the output.

<?php
  1. define('SITEURL','http://www.tutorialrays.com');
  2.       echo SITEURL;
  3. define('SITEURL','http://www.acesoftech.com');
  4.       echo SITEURL;
  5. ?>

Output :

As you can see in the above figure. We have changed constant value from http://www.tutorialrays.com to www.acesoftech.com but it prints the first value and not the acesotech.

What is a magic constant in PHP?

PHP has array of special predefined constants that change depending on where they are used. These constants are called magic constants. For example, the value of __DIR__ fetches the current directory name and shows it. Magic constants begin with two underscores and end with two underscores. The following section describes some of the most useful magical PHP constants.

A few "magical" PHP constants are given below −

Sr.No Name & Description 1 __LINE__ The current line number of the file. 2 __FILE__ It displays full path and filename of the file. If used inside an include,the name of the included file is returned. 3 __FUNCTION__ The function name. As of PHP 5 this constant returns the function name as it was declared (case-sensitive 4 __CLASS__ The class name. (Added in PHP 4.3.0) As of PHP 5 this constant returns the class name as it was declared (case-sensitive). In PHP 4 its value is always lowercased. 5 __METHOD__ The class method name. (Added in PHP 5.0.0) The method name is returned as it was declared (case-sensitive).