Zend PHP 5 – Basics – Constants

Constants

A constant is an identifier or name given for a simple value. The constants value cannot change during the execution of the script (except for magic constants).

The standard naming convention for constants are always uppercase.

We can define constants a couple of ways. The first is by using the define() function.

define("FOO", "something");
echo FOO; // Prints out "something"

The other way is by using the “const” keyword:

const MIN_VALUE = 0.0;

The define() method, if used in OOP should be used outside the class definition whereas const should be used inside the class definition.

<?php

define("FOO", "Something"); // Correct
const BAR = "Some other thing"; // Wrong

class MyClass
{
    const CONSTANT = 'Constant value'; // Correct
    define("BAZ", "Something else"); // Wrong

}

Class constant are by default public in nature but you cannot assign them a visibility as this results in a syntax error.

<?php
class MyClass
{
    const CONSTANT = 'constant value';
    public const OTHER_CONSTANT = 'other constant value'; // Syntax error

}

$class = new MyClass();
echo $class::CONSTANT; // Works
echo $class::OTHER_CONSTANT; // Doesn't work

Magic constants

PHP provides a large number of predefined constants to any script which it runs. Some of the constants change depending on where they are used. e.g. __LINE__ depends on the line that it’s used on in your script. Some of the magic constants are listed below:

  • __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__). Note that the directory name will 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).
  • __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.

Note: This article is based on PHP version 5.5.