PHP: Variables and constants. PHP data Php constant override
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:
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.0Comparison 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):
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?
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.