PHP Constants

Constants

Constants are like variables except that once they are defined they cannot be changed or undefined.

PHP Constants

A constant is an identifier (name) for a simple value. The value cannot be changed during the script.
A valid constant name starts with a letter or underscore (no $ sign before the constant name).
Unlike variables, constants are automatically global across the entire script.

Set a PHP Constant

You can define a constant by using the define() function or by using the const keyword outside a class definition

Example:

The following example creates a constant, using define() function named PIE with the value of 3.14

<?php
    $r = 10;
    define("PIE", 3.14);
    $area = PIE * $r * $r;
    echo $area;
?>

Output:

Tutorialik.com
314

Example:

The following example creates a constant, using const keyword named PIE with the value of 3.14

<?php
    $r = 10;
    const PIE = 3.14;
    $area = PIE * $r * $r;
    echo $area;
?>

Output:

Tutorialik.com
314

Deference between Constant vs Variable

  • Constants do not have a dollar sign ($) before them
  • Constants may only be defined using the define() function, not by simple assignment
  • Constants may be defined and accessed anywhere without regard to variable scoping rules
  • Constants may not be redefined or undefined once they have been set.

Predefined Constant

PHP provides large numbers of predefined constant to any script which it runs.
There are eight magic constant that change depending on where they are used.
For example, the value of __LINE__ depends in the line that it's used on in your script.
These special constant are case-insensitive.
The magical constant are listed in table below.

Name Description
__LINE__ The current line number of the file.
__FILE__ The full path and filename of the file with symlinks resolved. If used inside an include, the name of the included file is returned.
__DIR__ The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FUNCTION__ The function name.
__CLASS__ The class name. The class name includes the namespace it was declared in (e.g. Foo\Bar).
Note that as of PHP 5.4 __CLASS__ works also in traits. When used in a trait method, __CLASS__ is the name of the class the trait is used in.
__TRAIT__ The trait name. The trait name includes the namespace it was declared in (e.g. Foo\Bar).
__METHOD__ The class method name.
__NAMESPACE__ The name of the current namespace.


Share This Page to Download:

Share to Download

Share This Page on:


Ask Question

Basics of PHP