PHP constant override. Constants in PHP. What are constants used for and isn’t it easier to use variables?

Constants- these are values ​​that do not change over time. Even from school, you probably know many constants, for example, the number P, number e, acceleration free fall and others. And, of course, when programming, there is also very often a need to enter constants. And about how create and use constants in PHP, we'll talk about it in this article.

Let's go with you let's create a constant numbers P:

define(PI, 3.1415926);
echo PI;
?>

Operator define creates constant P.I. and assigns it a value 3.1415926 . Next we output 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 in capital letters. Not that this is necessary, but highly desirable. And this is customary not only in PHP, but in other languages ​​too.

Of course, later change constant PI will not be allowed (that’s why she constant).

Now let's look at one function that checks: " Is the given constant defined?". Let's write this script:

if (!defined("PI")) define(PI, 3.1415926);
echo PI;
?>

Here the existence of a constant is checked P.I.. And if it doesn't exist (that is define() function returned false), then we initialize this constant. Then we simply display it.

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

And finally, I would like to talk about built-in PHP constants. Let's write a simple script:

phpinfo();
?>

Towards the end there is a section " PHP Variable"Actually, this is not entirely constants however, they are constants when executing this script. Of course, when another script is executed, they will have different values ​​(not all, of course). Let's take you out as a couple constants, so that you understand how to work with them, because they are used incredibly often:

echo $_SERVER["REMOTE_ADDR"];
echo "
";
echo $_SERVER["QUERY_STRING"];
?>

In this script we output User IP address, which launched the script, and on the next line we display the query string (for example, " index.php?id=7"). Looking ahead a little, I say that here we are working with the global array $_SERVER. We will get to know arrays later, but I think that those who have worked with arrays in other programming languages ​​will recognize the syntax without any problems. As for others constants, then the work with them happens in the same way.

For each script executed. Many of these constants are defined by various modules and will only be present if those modules are available through dynamic loading or through static assembly.

There are nine magical constants that change their meaning depending on the context in which they are used. For example, the value __LINE__ depends on the line in the script on which this constant is specified. All magic constants are resolved at compile time, unlike regular constants, which are resolved at runtime. Special constants are case insensitive and are listed below:

Some magic PHP constants
Name Description
__LINE__ The current line number in the file.
__FILE__ Full path and name of the current file with expanded symlinks. If used inside an included file, the name of this file is returned.
__DIR__ File directory. If used inside an included file, the directory of that file is returned. This is equivalent to calling dirname(__FILE__). The returned directory name does not end with a slash, except for the root directory.
__FUNCTION__ Function name or (closure) in the case of an anonymous function.
__CLASS__ Class name. This name contains the name of the namespace in which the class was declared (for example, Foo\Bar). Please note that since PHP 5.4 __CLASS__ also works in traits. When used in trait methods, __CLASS__ is the name of the class in which the methods are used.
__TRAIT__ Trait name. This name contains 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 name class (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=new trick();
$obj->doit();
output will be ---- doit
$obj->doitagain();
output will be ----- trick::doitagain

13 years ago

The __CLASS__ magic constant nicely complements 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 = new derived_class();

$obj_b -> say_a();
echo "
" ;
$obj_b -> say_b();

?>

The output should 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 advertised 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 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 can or 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

Last update: 11/1/2015

Constants, like variables, store a specific value, but unlike variables, the value of constants can be set only once, and then we cannot change it. For example, let's define a numerical constant:

To define a constant, use the define operator, which has the following form: define(string $name, string $value, bool $case_sen=false) . The $name parameter conveys the name of the constant, and the $value parameter conveys its value. The third optional parameter takes a boolean true or false . If the value is false, then when using a constant its case will be taken into account; if true, case will not be taken into account. In our case, the third parameter is not used, so it is false by default.

After defining a constant, we can use it just like a regular variable. The only exception is that we will not be able to change its value. Another difference with a variable is that you do not need to use the $ sign. That is, the expression NUMBER=33; won't work.

Predefined Constants

In addition to programmer-created constants, PHP has several built-in constants:

    FILE__ : stores the full path and name of the current file

    LINE__ : stores the current line number that the interpreter is processing

    DIR__: stores the directory of the current file

    FUNCTION__ : name of the function being processed

    CLASS__ : name of the current class

    METHOD__ : name of the method being processed

    NAMESPACE__ : name of the current namespace

For example, let's print the current line being executed and the file name:

Checking the existence of a constant

To check if a constant is defined, we can use the bool defined(string $name) function. If the constant $name is defined, the function will return true

A constant is an identifier (name) for a simple value. As the name suggests, their value cannot change during script execution (except for magic constants, which are not actually constants). Constant names are case sensitive by default. By convention, constant names are always written in upper case.

The name of a constant must follow the same naming conventions as other names in PHP. A valid name begins with a letter or underscore followed by any number of letters, numbers, and underscores. Regular expression to check the correctness of the constant name it looks like this: ^*$

It is possible to define constants using a function define() reserved or even invalid names whose values ​​can (only) be obtained via a function constant(). However, this is not recommended.

Example #1 Correct and incorrect constant names

// Correct constant names
define ("FOO" , "something" );
define ("FOO2" , "something else" );
define ("FOO_BAR" , "something more" );

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

// This is a valid declaration, but it's better not to use it:
// PHP may one day register a magic constant,
// which will break the script
define ("__FOO__" , "something" );

?>

Comment: The concept of "letters" here is characters 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 are the same with the 5.x

using a constant declared by DEFINE("CNS",value) : 0.63575601577759s
using a constant declared by const CNS=value: 0.61372208595276s
using a variable declared by $v=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=microtime(true);
$x=0;
for($i=0;$i<50000000;$i++) {
$x+=CNS;
}
$p2=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 == 1 ) (
// echo some sensitive data.
}
?>

Now it works correctly.

In this post we will figure out what the difference is in PHP ad constants using the const keyword and the define() function.

Constants in PHP are “constant” whose values ​​are specified only once and then cannot be changed. If you try to change the value, it will not change and a PHP note will appear: “Constant already defined”:

Define("FOO", "val"); define("FOO", "val2"); // Notice: Constant already defined echo FOO; //> val

There are two ways to declare constants in PHP:

// 1 define("NAME", "VALUE"); // 2 const NAME = "VALUE";

Each method has its own characteristics, to understand them, let's look at everything step by step, how and what changed with each version of PHP.

How to create constants

PHP less than 5.3

Before 5.3 in PHP, constants could only be defined using define() . The const keyword appeared in version 5.3.

Only scalars can store constants. Scalar variables are variables with types integer, float, string and boolean. The array, object, and resource types are not scalar.

// scalars define("FOO", 10); define("FOO", 10.9); define("FOO", "val"); define("FOO", true); // not scalars define("FOO", array(1)); // the constant is not set and we get Warning define("FOO", (object) array(1)); // the constant is not set and we get a Warning

From PHP 5.3

Appeared keyword const and now a constant can also be defined using it.

However, you cannot specify a variable, function or some kind of expression in const, but you must pass the scalar “directly”:

Const FOO = "val"; // no errors const FOO = $var; // Parse error const FOO = home_url(); // Parse error const FOO = 5 + 10; // Parse error const FOO = "foo"."bar"; // Parse error

Whereas for define() there are no such restrictions...

Define("FOO", "val"); // no errors define("FOO", $var); // no errors define("FOO", home_url()); // no errors define("FOO", 5 + 10); // no errors define("FOO", "foo"."bar"); // no mistakes

PHP 5.6

It has become possible to specify primitive PHP expressions (expressions from scalars) as const values:

Const FOO = 1 + 2; const FOO = "foo" . "bar";

It has become possible to store arrays in constants:

Const FOO = ; // works define("FOO", ); // doesn't work in PHP 5.6, works in PHP 7.0

Difference between define() and const

#1 const must be declared in the top scope

Unlike define() , const must be declared at the very top of the scope because they are defined when the script is compiled. This means that they cannot be declared inside functions/loops/if statements or try/catch blocks.

If (1) ( const NAME = "VALUE"; // does not work ) // but if (1) ( define("NAME", "VALUE"); // works )

#2 const is always case sensitive

const is always case-sensitive, while define() allows you to make case-insensitive constants:

Define("NAME", "VALUE", true); echo NAME; // VALUE echo name; // VALUE

#3 const only understands scalars

This is only valid for PHP versions 5.6 and below...

const cannot be passed to variables, functions, expressions, but define() can be:

Const FOO = $var; // Parse error const FOO = home_url(); // Parse error define("FOO", $var); // no errors define("FOO", home_url()); // no mistakes

#4 const can store arrays since PHP 5.6 and define since PHP 7.0

const FOO = ; // works in PHP 5.6 define("FOO", ); // doesn't work in PHP 5.6, works in PHP 7.0
Comparison results

It is almost always better to define a constant using define() , because there are more possibilities and fewer options to “catch” an error... The exception is when you have PHP 5.6 and you need to save the array to a constant, const will help here.

PHP class constants

They are declared only using const . The rules for them are as described above: they accept only scalars, do not understand PHP variables, functions, expressions...

Class constants are always public - there is no private or protected status.

The declared constant belongs specifically to the class, it does not belong to any object and is common to all objects (instances) of the class.

Class My_Class ( const NAME = "VALUE"; // starting with PHP 5.6 you can use mathematical expressions const SEC_PER_DAY = 60 * 60 * 24; function print_name() ( // accessing a class constant inside a method via self (the class itself) echo self ::NAME; ) ) // access to a constant outside the class // can be called from the global scope without initializing a class instance echo My_Class::NAME;

Class constants are very similar to static class properties.

Class My_Class ( const NAME = "VALUE"; static $name = "VALUE";; ) echo My_Class::NAME; echo My_Class::$name;

"Magic" constants

And in conclusion, let's remember about special PHP constants...

PHP has nine magic constants that change their meaning depending on the context in which they are used. For example, the value of __LINE__ depends on the line in the script on which this constant is specified. All "magic" constants are resolved at compile time, unlike regular constants, which are resolved at runtime. Special constants are case insensitive and are listed below:

Constant Description
__LINE__ The current line number in the file.
__FILE__ The full path and name of the current file in which the constant is called.
__DIR__ PHP 5.3.0. The directory of the file in which the constant is used. Same as dirname(__FILE__) . Does not have a trailing slash, except in the root directory.
__FUNCTION__ Function name.
__CLASS__ Class name. This name contains the name of the namespace in which the class was declared (for example, Foo\Bar). Also works in traits. When used in trait methods, this is the name of the class in which these methods are used.
__TRAIT__ PHP 5.4.0. Trait name. 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__ PHP 5.3.0. The name of the current namespace.
ClassName::class PHP 5.5.0. Full class name (including namespace). Also see::class.