This post covers the Operators section of the PHP Basics chapter when studying for the Zend PHP 7 Certification.
A constant is an identifier given for a simple value. The value for non-magic constants cannot change during the execution of the script.
The naming convention of a constant follows the same rules as labelling a variable, however by default, constants are always uppercase.
We can define constants a couple of ways. The first is by using define()
, and the second is by using const
.
define("FOO", "something");
echo FOO; // Prints out: something
const MIN_VALUE = 1;
echo MIN_VALUE; // Prints out 1
If your constant has been declared using define()
, if used in OOP should be used outside the class definition. const
can be used inside and outside the class definition.
<?php
define("FOO", "Something"); // Correct
const BAR = "Some other thing"; // Correct
class MyClass
{
const CONSTANT = 'Constant value'; // Correct
define("BAZ", "Something else"); // Wrong
}
Prior to PHP 5.6, it was only possible for a constant to contain scalar data (string, int, bool, float)
From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant.
const THREE = TWO + 1;
const ONE_THIRD = ONE / self::THREE;
const SENTENCE = 'The value of THREE is '.self::THREE;
const ARR = ['a', 'b'];
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';
}
$class = new MyClass();
echo $class::CONSTANT; // Works
echo $class::OTHER_CONSTANT; // Error
With PHP 7.1, you can use visibility with 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. For example, __LINE__
depends on the line that it’s used on in your script.
The nine magic constants that PHP provides can be seen 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.ClassName::class
– The fully qualified class name.View the other sections:
Note: This article is based on PHP version 7.0.