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 are magical PHP constants
Name Description
__LINE__ The current line number in the file.
__FILE__ Full path and the 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 class name (including 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

12 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

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 uppercase.

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. A regular expression for checking the correctness of a constant name 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 errors

PHP 5.6

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

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 errors

#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.

A variable is an entity containing data. If a data type is a general description of the format of stored data and how to work with it, then a variable represents a specific block of computer memory. This block stores variable value, and you can access the block (and the value) using variable name.


In PHP, a variable name always begins with a dollar sign ($), which must be followed by a letter, after which you can use letters, numbers, and an underscore. Names are case sensitive, i.e. the variables $value, $Value, $VALUE and $VaLuE are four DIFFERENT variables, although their name reads the same.

Examples of syntactically correct variable names:

Example of incorrect names:

There is one general rule (for all programming languages) regarding variable naming. The rule is very simple: names should always be meaningful.

Example of poorly readable code

Brevity, of course, is the essence of talent, but sacrificing the ease of perception of code for the sake of its compactness is unwise. Moreover, the length of the name does not affect the performance of the script in any way. But you shouldn’t go to the opposite extreme - giving variables names that are too long. If the name must consist of two or more words, parts of the name must be capitalized or separated by underscores. For example, name $strusernameadndomain much better perceived in the form $str_UserNameAndDomain.

Example of highly readable code

There are two types of variables: regular variables(value variables) and reference variables. The key difference between them is the way they process data. When assigning a value to a regular variable, the assigned value is completely copied, i.e. a new memory block is created where a copy of the original value is placed. During further work, all changes will be reflected on this copy, and not on the original data.

Reference variables work differently. When assigning a value to a reference variable, it is not the data that is copied, but information about where it is located. The result is that the variable points to the same block in which the original data lies. Now if you change the value of the reference variable, the original value will change.

Let's look at an example:

Passing variables by value

There are special functions in PHP for working with variables:

  • isset() - checks whether a variable has been declared and whether its value is different from NULL;
  • empty() - analogue of isset()
  • unset() is a built-in language function that removes the value of a variable and removes the variable itself from the list of available variables (destroying the variable).

Variable Scope

Very important characteristic variable - its scope (scope), i.e. a description of where in the program (script) its value can be read or changed. You should always remember that a variable declared inside a program block is visible only within that block, and in order to access a variable declared outside the block, it must be declared in a special way.

The program blocks in this case are “script”, “function” or “class”. For example:

Everything seems to be correct, but it doesn’t work. Why? Because unless you explicitly say that the variable $name inside a function is actually the global variable $name, then the interpreter will create a temporary copy of the variable with the name $name and an empty value. And since the value is empty (undefined), the result of adding strings will be undefined (empty).

Correcting the situation is very easy, just add one line (in bold):

global $name; // explicitly indicate that we should // use a global variable.$fullName = $name . $family; echo "Name inside function: ".$fullName; ) echo "Name BEFORE the function call: ".$name; // result: "Name BEFORE calling the function: Vasya" tryChengeName("Ivanov"); // result: "Name inside the function: Vasya Ivanov" echo "Name AFTER the function call: ".$name; // result: "Name AFTER calling the function: Vasya Ivanov" ?>

In this example, the $name variable has a scope equal to the entire script, and the $fullName variable, declared inside a function, has a scope equal to the function itself. This means that when their function exits, the $fullName variable will be destroyed, and all attempts to read its value will result in an error.

We will look at examples of working with classes in the “Classes and Inheritance” section.

Variable variables

Yes, yes, there is no error here, this is exactly what (in two words) some variables are called in PHP. The idea is that the text part of a variable name (i.e. the name without the dollar sign) can itself be a name. For example:

It is strongly recommended not to use such techniques unless absolutely necessary. Code stuffed with such tricks is very difficult to maintain. This is especially important when working with data entered by users. The main cause of complexity is implicit dependencies. For example, what happens if instead of the name “Vasya” you write something like """""_;%//^q""? Right! In most cases the script will not be able to execute! You can, of course, add a bunch of checks for the presence of “wrong” characters, but it’s easier not to use such tricks at all.

Constants

A constant is a certain unchanging value. A constant is declared with both a name and a value. To declare a constant, use the function define(), and to determine the presence of a constant (i.e. whether it was defined or not) - the function defined(). The name of a constant is constructed according to the same rules as the names of variables.

Examples of constants:

A separate type of PHP constants are the so-called “magic constants”. These are system constants whose value is determined and set by the interpreter. There are a few such constants:

  • __LINE__ Contains the current line number in the current file.
  • __FILE__ Contains the full name of the current file
  • __FUNCTION__ Contains the name of the current function.
  • __CLASS__ Contains the name of the current class.
  • __METHOD__ Contains the name of the current method of the current class.

These constants are very convenient for debugging, but in all other cases it is better not to use them, replacing them with calls to the corresponding functions.

» Constants in PHP?

Navigation through the Tutorial: 1.1 About PHP 1.2 History of PHP 1.3 Why PHP? 1.4 How does it all (PHP) work? 1.5 From interpreter to compiler 1.6 PHP capabilities 1.7 What is needed to work? 1.8 Answers to your questions 1.9 Conclusion to the chapter 2.1 Installation and configuration 2.2 Installing Apache 2.3 Installing PHP 2.4 Installing MySQL 2.5 Setting up Apache 2.6 PHP setup 2.7 Setting up MySQL 2.8 Testing Apache, PHP programs 2.9 Conclusion to Chapter 2 3.1 PHP language syntax 3.2 Professional insertion 3.3 PHP and HTML 3.4 Comments in the language (code) PHP 3.5 PHP styling program code 3.6 Conclusion to Chapter 3 4.1 Variables. What are variables? 4.2 Variables Data types in PHP 4.3 Integer. Data type. 4.4 Double. Data type. 4.5 Boolean. Data type. 4.6 Other data types 4.7 Defining variables in PHP 4.8 Changing data type in PHP 4.9 Variable references in PHP 4.10 Dynamic variables in PHP 4.11 What are Constants in PHP? 4.12 Defining constants in PHP 4.13 Predefined constants in PHP 4.14 Conclusion to Chapter 4 5.1 Operators in PHP 5.2 Assignment operator in PHP 5.3 Arithmetic operators in PHP 5.4 Relational operators in PHP 5.5 Logical operators in PHP 5.6 Bitwise operators in PHP 5.7 String operators in PHP 5.8 Error Suppression Operator in PHP 5.9 Increment and Decrement Operators in PHP 5.10 Shorthand for Variable Assignment in PHP 5.11 Precedence and Associativity in PHP 5.12 Conclusion to Chapter 5 6.1 Control Statements in PHP 6.2 Conditional operator IF 6.3 Conditional Statement Elseif 6.4 Conditional Statement Switch 6.5 Statements For loop 6.6 Operator While loop 6.7 Do...while Loop Statement 6.8 Unconditional Break Statement 6.9 Unconditional Continue Statement 6.10 Unconditional Exit Statement 6.11 Require 6.12 Include 6.13 Conclusion to Chapter 6 7.1 Functions in PHP 7.2 Defining Functions in PHP 7.3 Function Arguments in PHP 7.4 Variable Scope 7.5 Lifetime variables in PHP 7.6 Recursion in PHP 7.7 Dynamic function calls in PHP 7.8 Conclusion to Chapter 7 8.1 Arrays in PHP 8.2 Assigning values ​​to PHP arrays 8.3 Function array () PHP 8.4 Outputting PHP arrays 8.5 Traversing PHP arrays. count() function, foreach() constructs 8.6 reset() function 8.7 each() 8.8 list() 8.9 Adding arrays 8.10 Comparing arrays 8.11 Adding array elements 8.12 Removing array elements 8.13 Sorting arrays 8.14 Multidimensional arrays 8.15 Converting to an array 8.16 Conclusion to Chapter 8 9.1 String 9.2 Handling variables within strings 9.3 Outputting strings 9.4 Formatted output of strings 9.5 Length of a string in PHP 9.6 Finding a substring in a string 9.7 Cleaning strings 9.8 Conclusion to Chapter 9 10.1 Working with HTML forms 10.2 Passing data HTML forms. GET and POST method 10.3 Receiving data in PHP 10.4 Superglobal arrays $_GET and $_POST 10.5 Conclusion to Chapter 10 11.1 Opening files in PHP 11.2 Closing files in PHP 11.3 Reading and writing files in PHP 11.4 Copying, deleting and renaming files in PHP 11.5 Receiving file information in PHP 11.6 File index in PHP 11.7 Opening and closing directories in PHP 11.8 Reading directories in PHP 11.9 Creating and deleting directories in PHP 11.10 Conclusion to Chapter 11 12.1 Working with MySQL databases in PHP 12.2 Connecting PHP to the MySQL database server 12.3 Creating and deleting a MySQL database 12.4 Creating and deleting MySQL tables 12.5 Working with MySQL data 12.6 Conclusion to Chapter 12 13.1 Working with images in PHP. GD Library 13.2 Creating and displaying images in PHP 13.3 Modifying images in PHP 13.4 Working with text in PHP 13.5 Conclusion to Chapter 13 14.1 Working with date and time in PHP 14.2 Date and time formatting symbols in PHP 14.3 Date() and getdate() function in PHP 14.4 Conversions to absolute time in PHP 14.5 Conclusion to Chapter 14 15.1 Working with regular expressions in PHP 15.2 POSIX regular expressions in PHP 15.3 Metacharacters in PHP 15.4 Character classes 15.5 Quantifiers 15.6 Pattern substitution 15.7 Regular expression examples 15.8 Conclusion to the chapter 15 16.1 Working with Cookies in PHP 16.2 Creating Cookies in PHP 16.3 Reading from Cookies 16.4 Deleting Cookies 16.5 Conclusion to Chapter 16

Using in everyday life the word "constant", we mean constant meaning. This could be the number Pi (3.14) or the boiling point of water (100 °C). PHP also has the ability to use constants. The point of using them is that having designated a certain value, we can use it throughout the entire program code.

(!) A constant is an unchangeable value.

For example, your friend Vasily Pupkin created a Web site and wants everyone to know the administrator's name. At the same time, he finds the simplest and, at first glance, correct solution (Listing 4.19).

Listing 4.19. Displays the last name and first name of the Web site administrator.

‹?php
echo "Site administrator: Vasily Pupkin"; // message output
?›

Accordingly, you need to change the administrator name. Most likely, you will search all pages of the site for text containing the line Pupkin Vasily. After finding it, you need to figure out whether to change it to your name or not. It is not difficult to notice that solving a seemingly simple problem takes a lot of time and does not guarantee the correct operation of the program. All these problems could have been avoided if Vasily had used a constant to represent his name. To do this, you need to select the name of the constant (usually called an identifier), for example ADMIN_NAME, and then determine its value (in our case, Vasily Pupkin).

The solution to the problem will now look like the one shown in Listing 4.20.

Listing 4.20. An example of using constants.

‹html›
‹head›
‹title›Example of using constants‹/title›
‹/head›
‹body›
‹?php
define("ADMIN_NAME", "Pupkin Vasily"); // definition of a constant
echo "Site Administrator: "; // message output
echo ADMIN_NAME; // output the value of the constant
?›
‹/body›
‹/html›

In this case, the ADMIN_NAME identifier will be replaced by the value Pupkin Vasily. In order to change the name of the Web site administrator, you only need to adjust the line with the definition of the constant. Let's look at this topic in more detail.


Close