PHP Tutorial Tutorials - PHP Constants

PHP Constants
  • Constants are used for storing fixed values. Once they are defined, they cannot be undefined or changed.
  • The scope of a constant is global.

Using define() function to define a constant

<?php
// Defining constant
define("WEBSITE", "http://www.lautturi.com");
 
echo 'Welcome to visit - ' . WEBSITE;
?>

A valid constant name starts with a letter or underscore, followed by any number of letters, numbers, or underscores.

// Invalid constant names
define("2FOO",    "something");

Using the keyword const to define a constant

<?php
const HOST = 'Lautturi.com';

echo "Hello ".HOST;
?>

Magic constants

PHP provides some predefined constants,they are called "magical" constants.

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, or {closure} for anonymous functions.
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.

ClassName::class The fully qualified class name. See also ::class.

<?php
    echo "The script file is:".__FILE__;
    echo PHP_EOL;
    echo "The current line number:".__LINE__;
?>

Output:

The script file is:D:\Apache24\htdocs\index.php
The current line number:4
Date:2019-10-01 01:06:25 From:www.Lautturi.com author:Lautturi