Constants in PHP. Frequently Asked Questions (FAQ): Things you need to know about namespaces Creating PHP Constant

There are cases where the variables are quite inconvenient to use any specific values \u200b\u200bfor constant storage that do not change during the program. These values \u200b\u200bcan be mathematical constants, paths to files, a variety of passwords, etc. Just for these purposes in PHP there is such a design as.

called a named value that does not change during the program execution (script).

In the RNR constants are determined by the function define () . This feature has the following format:

define ($ Name., $ value, $ Case_Sen.), Where:

$ Name. - the name of the constant;
$ value - value constant;
$ Case_Sen. - optional parameter of logical type,
Indicating whether the case of letters (TRUE) or not (false) should be considered.

An example of determining and using PHP constants:


echo Pi;
// displays 3.14.
?>

If the parameter $ Case_Sen. Raven true.The interpreter will take into account the symbol register when working with the constant. Please note that the constants are used without a preceding sign. $ .

Differences between constants and variables:

    CONSTANT no console in the form of a dollar sign ( $ );

    Constants can be defined only using the function define () and not assigning value;

    Constants can be defined and available anywhere without taking into account the scope;

    Constants cannot be determined or canceled after the initial ad;

    Constants can only have scalar values.

Verification of the existence of constants

To verify the existence of the constant, you can use the function defined () . This feature returns true.if the constant is declared. Let us give an example:

// declare a PI constant
define ("PI", 3.14, True);
if (defined ("PI") \u003d\u003d TRUE) ECHO "Pi Constant is announced!";
// The script will display "PI constant is announced!"
?>

Predefined PHP constants

The following predefined constants exist in PHP:

PHP provides a large list of predefined constants for each executable script. Many of these constants are determined by various modules and will be present only if these modules are available as a result of a dynamic load or as a result of static assembly.

There are five predefined constants that change their value depending on the context in which they are used. For example, Constanta __Line__ Depends on the row in the script on which this constant is indicated. Special constants are insensitive to the register and their list is shown below:

Name Description
__Line__ Current line in the file.
__File__ The full path and name of the current file.
__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 Tradition Slash Unless It Is The Root Directory.
__Function__ The name of the function. (Added to PHP 4.3.0.)
__Class__ Class name. (Added to PHP 4.3.0.)
__Trait__ The Trait Name. The Tait Name Includes The Namespace It Was Declared in (E.G. Foo \\ Bar).
__Method__ The name of the class method. (Added to PHP 5.0.0)
__Namespace__ The Name of the Current Namespace.

Additionally

Constant is an identifier (name) for a simple value. As it follows from the name, their value cannot change during the execution of the script (except magic constants, which are not actually constants). The default constants are sensitive to the register. According to the adopted agreement, the names of the constants are always written in the upper case.

The name of the constant must comply with the same naming rules as other names in PHP. The correct name begins with the letter or underlining symbol, followed by any number of letters, numbers and underscore characters. A regular expression for checking the correctness of the name constant looks like this: ^ * $

It is possible to determine the constants using the function define () Reserved or even incorrect names whose values \u200b\u200bmay be (only) are obtained through the function constant (). However, it is not recommended.

Example # 1 Correct and Incorrect Constant Names

// Right Names of Constant
dEFINE ("FOO", "Something");
define ("FOO2", "Something else");
define ("Foo_Bar", "Something more");

// Incorrect Constant Names
define ("2Foo", "Something");

// This is a faithful announcement, but it is better not to use it:
// php once can register a magic constant,
// which violates the work of the script
define ("__foo__", "Something");

?>

Comment: The concept of "letters" here is symbols A-Z, A-Z, and other characters with ASCII codes from 128 to 255 (0x80-0xFF).

2 Years Ago.

Performance of Constants. PHP 7.1.10 32 Bits (Opcache Active, Windows 10 i7-64Bits) But Apparently The Trends Is The Same With The 5.x

using a Constant Declared by Define ("CNS", Value): 0.63575601577759S
using a constant declared by const CNS \u003d Value: 0.61372208595276s
using a variable declared by $ v \u003d value: 0.51184010505676s

In Average, The Use of Define and Const Is Around The Same with Some Sightly Better Performance of Const Instead Of Define. However, using a Variable IS Around 10-50% Better Than to Use a Constant. SO, For a Performance Intensive Task, Constant Is Not The Best Option.

$ p1 \u003d microtime (true);
$ x \u003d 0;
for ($ i \u003d 0; $ i<50000000;$i++) {
$ x + \u003d CNS;
}
$ P2 \u003d Microtime (TRUE);

14 YEARS AGO.

An undefined Constant Evaluates As True WHEN NOT USED CORRECTLY. Say for Example You Had Something Like This:

settings.php.
// Debug Mode.
define ("Debug", False);
?>

test.php.
iNCLUDE ("settings.php");

if (Debug) (
// Echo Some Sensitive Data.
}
?>

If For Some Reason Settings.php Doesn "T GET INCLUDED AND THE DEBUG CONSTANT IS NOT Set, PHP Will Still Print The Sensitive Data. The Solution is to Evaluate It. Like SO:

settings.php.
// Debug Mode.
define ("Debug", 0);
?>

test.php.
iNCLUDE ("settings.php");

if (Debug \u003d\u003d 1) (
// Echo Some Sensitive Data.
}
?>

Now It Works Correctly.

Last updated: 1.11.2015

Constants, as well as variables store a specific value, only in contrast to variables The value of the constant can be installed only once, and then we can no longer change it. For example, we define a numerical constant:

To determine the constant, the Define operator is used, which has the following form: Define (String $ Name, String $ Value, BOOL $ CASE_SEN \u003d FALSE). The Name parameter transmits the name of the constant, and the $ value parameter is its value. The third optional parameter receives the logical value TRUE or FALSE. If the value is false, then when using the constant will be taken into account its register if true - the register is not taken into account. In our case, the third parameter is not used, so it is equal to False by default.

After determining the constant, we can use it as well as the usual variable. The only exception - we will not be able to change its meaning. Another difference from the variable is not to use the $ sign. That is, the expression number is Number \u003d 33; It will not work.

Predefined constants

In addition to the programmer created by the programmer, there are several more built-in constants in PHP:

    File__: Stores the full path and name of the current file

    Line__: Stores the current line number that interpreter processes

    Dir__: Stores the current file directory

    Function__: Name of the processed function

    Class__: The name of the current class

    Method__: The name of the processed method

    Namespace__: Name of the current namespace

For example, withdraw the current executable string and file name:

Checking the existence of the Constanta

To check whether the constants are defined, we can use the BOOL DEFINED (STRING $ NAME) function. If $ Name constant is defined, the function will return to True

Constants - These are values \u200b\u200bthat do not change over time. From school you probably know many constants, for example, the number p, Number e., acceleration of free fall and others. And, of course, when programming also, very often the need for input constant. And about how create and use PHP constants, We will talk in this article.

Let's with you create a constant numbers p:

Define (PI, 3.1415926);
Echo Pi;
?>

Operator define Creates constanta PI and assigns the meaning 3.1415926 . Then we bring this constant through the operator echo.. Everything is very simple, however, there is one recommendation that I advise you to always follow. Be sure to write constants capital letters. Not that it was necessarily, but extremely desirable. And so accepted not only in Php., but in other languages \u200b\u200btoo.

Of course, afterwards change constant PI will not be (on that constant).

Now we will analyze one function that checks: " Is a given constant defined". Let's write such a script:

if (! Defined ("PI")) Define (PI, 3.1415926);
Echo Pi;
?>

Here the existence of constant is checked PI. And if it does not exist (that is define () function Vernoil false), then initialize this constant. Then just withdraw it.

As you can see, create and use your constants in PHP. - It's very simple.

And, finally, I want to tell about built-in PHP Constants. Let's write a simple script with you:

phpinfo ();
?>

Closer to the end there is a section " PHP Variable."Actually, this is not quite constants, however, they are constanta When performing this script. Of course, when performing another script, they will already have other values \u200b\u200b(not everything, of course). Let's bring a couple with you constantso that you understand how to work with them, because they are used insanely often:

Echo $ _Server ["remote_addr"];
Echo "
";
Echo $ _Server ["query_string"];
?>

In this script we derive User's IP addressrunning the script, and on the next line we display the query string (for example, " index.php? id \u003d 7"). Looking a little forward, saying here we work with the global an array of $ _Server.. We still meet with arrays, but I think that those who have worked with arrays in other programming languages, syntax recognize without problems. As for others constant, then with them work occurs similarly.

For each executable script. Many of these constants are determined by various modules and will be present only if these modules are available as a result of a dynamic load or as a result of static assembly.

There are nine magical constants that change their value depending on the context in which they are used. For example, value __Line__ Depends on the row in the script on which this constant is indicated. All magic constants are allowed during compilation, in contrast to conventional constants that are allowed during execution. Special constants are insensitive to the register and their list is shown below:

Some magic PHP constants
Name Description
__Line__ Current line number in the file.
__File__ The full path and name of the current file with deployed simlinks. If used inside the plug-in file, then the name of this file is returned.
__Dir__ File directory. If used inside the plug-in file, the directory of this file is returned. This is equivalent to calling dirname (__ File__). The return name of the directory does not end on the lay, with the exception of the root directory.
__Function__ Function name or (Closure) In case an anonymous function.
__Class__ Class name. This name contains the name of the namespace, in which the class was announced (for example, Foo \\ Bar.). Please note that starting with PHP 5.4 __Class__ also works in traits. When used in the methods of Traits __Class__ is the name of the class in which these methods are used.
__Trait__ The name of the trait. This name contains the name of the namespace, in which the trait was declared (for example, Foo \\ Bar.).
__Method__ The name of the class method.
__Namespace__ The name of the current namespace.
Classname :: class Full class name (indicating the namespace). See also :: Class.

see also get_class (), get_object_vars (), file_exists () and function_exists ().

List of changes

14 YEARS AGO.

The Difference Between.
__Function__ and __method__ as in php 5.0.4 is that

FUNCTION__ RETURNS ONLY THE NAME OF THE FUNCTION

wHILE AS __METHOD__ RETURNS THE NAME OF THE CLASS ALONGWITH THE NAME OF THE FUNCTION

class Trick.
{
FUNCTION DOIT ()
{
echo __function__;
}
FUNCTION DOITAGAIN ()
{
Echo __Method__;
}
}
$ OBJ \u003d new trick ();
$ OBJ-\u003e DOIT ();
oUTPUT WILL BE ---- DOIT
$ OBJ-\u003e DOITAGAIN ();
output Will Be ----- TRICK :: DOITAGAIN

13 Years Ago.

The __Class__ Magic Constant Nicely Complempments The Get_class () function.

Sometimes You Need to Know Both:
- Name of the Inherited Class
- Name of The Class Actually Executed

Here "S An Example That Shows The Possible Solution:

Class Base_Class.
{
Function Say_a ()
{

" ;
}

Function Say_B ()
{

" ;
}

class Derived_Class Extends Base_Class
{
Function Say_a ()
{
parent :: Say_a ();
Echo "" A "- SAID THE". __Class__. "
" ;
}

Function Say_B ()
{
parent :: Say_B ();
Echo "" B "- Said The". get_class ($ this). "
" ;
}
}

$ OBJ_B \u003d new derived_class ();

$ OBJ_B -\u003e SAY_A ();
echo "
" ;
$ OBJ_B -\u003e Say_B ();

?>

The Output Shld Look Roughly Like This:

"A" - SAID THE BASE_CLASS
"A" - SAID THE DERIVED_CLASS

"B" - SAID THE DERIVED_CLASS
"B" - SAID THE DERIVED_CLASS

3 Years Ago.

Note a small inconsistency when using __CLASS__ and __METHOD__ in traits (stand php 7.0.4): While __CLASS__ is working as advertized and returns dynamically the name of the class the trait is being used in, __METHOD__ will actually prepend the trait name instead of the Class Name!

8 Years Ago.

There Is No Way to Implement A Backwards Compatible __dir__ in Versions Prior to 5.3.0.

The Only Thing That You Can Do Is To Perform A Recursive Search and Replace to Dirname (__ File__):
find. -Type f -Print0 | Xargs -0 Sed -i "S / __ DIR __ / DIRNAME (__ File __) /"

5 Years Ago.

A Lot of Notes Here Concern Defining The __dir__ Magic Constant for Php Versions Not Supporting The Feature. Of Course You Can Define This Magic Constant for PHP Versions Not Yet Having This Constant, But It Will Defeat Its Purpose As Soon As You Are A using the Constant in An Included File, Which May Be in A Different Directory Then The File Defining the __dir__ Constant . AS Such, The Constant Has Lost Its * Magic *, and Would Be Rather Useless Unless You Assure Yourself to Have All of Your Includes in the Same Directory.

Concluding: Eye Catchup at Gmail Dot COM "S Note Regarding Whether You Cannot Define Magic Constants Is Valid, But Stating That Defining __dir__ is Not Useless, IS NOT!

7 Years Ago.

You Cannot Check If a Magic Constant Is Defined. This Means There Is No Point In Checking If __dir__ is Defined Then Defining IT. `Defined (" __ dir __ ")` Always Returns False. Defining __dir__ Will Silently Fail In PHP 5.3+. This Could Cause Compatibility Issues If Your Script Includes Other Scripts.

echo (Defined ("__dir__")? "__dir__ is defined": "__dir__ is not defined." PHP_EOL);
echo (Defined ("__file__")? "__File__ IS Defined": "__file__ is not defined." PHP_EOL);
eCHO (DEFINED ("PHP_VERSION")? "PHP_VERSION IS Defined": "PHP_VERSION IS NOT DEFINED"). Php_eol;
echo "PHP Version:". Php_version. Php_eol;
?>
Output:
__Dir__ is not defined
__File__ is not defined
PHP_VERSION IS Defined.
PHP Version: 5.3.6