PHP data. Php constants overriding constants
Hello. Today I decided to write about constants in PHP. I’ll tell you how constants work, which ones are most often used and exist.
What are constants in the context of PHP?
Constants are essentially variables whose value cannot be redefined. That is, after specifying their value, you will no longer be able to change it during the execution of the script. They are usually written in upper case and the name specifically reflects the information stored in them.
There are 2 types of constants in PHP:
- Regular (set by the programmer)
- Predefined (set by the interpreter)
Ordinary constants
This type of constants is usually used for official purposes and is created by the programmer in the process of writing code.
The syntax for creating a regular constant is:
Define("PI",3.1415);
A constant is created using a built-in construct define ("Constant name","Constant value").
To briefly explain the mechanism of working with constants, I will show an example of the fact that the values in constants are set once and cannot be changed again:
In order to check the existence of a constant, the language provides a function defined("CONST_NAME").
Predefined Constants
Predefined constants are different from in the usual way creation. They are set by the interpreter itself and change their meaning in the context of program execution. They are also not case sensitive, __CLASS__ or __class__ will be perfectly executed by the interpreter.
Here are the most commonly used predefined constants:
- __FILE__— stores the name of the currently running script.
- __FUNCTUIN__— name of the current function.
- __CLASS__— name of the current class.
- PHP_VERSION— contains the version of the PHP interpreter.
- TRUE, FALSE, NULL- contain meanings corresponding to their name.
For an example of how such constants work, let’s look at the use of one of them - __FUNCTION__:
As you can see from the example, the constant __function__ returned the name of the function in which it was originally called - abc().
And yes, a constant cannot be deleted as usual variable by function unset(), it exists from the beginning to the end of program execution.
That's all, I wish you successful practice and good mood. See you soon.
website Content rights reserved.Constants are identifiers (names) of simple values. Based on their name, it is easy to understand that their value cannot change during script execution (exceptions are "magic" constants, which are not actually constants in the full sense of the word). Constant names are case sensitive. By convention, constant names are always written in upper case.
The name of a constant must follow the same rules as other names in PHP. A valid name begins with a letter or underscore and consists of letters, numbers, and underscores. A regular expression for checking the correctness of a constant name looks like this: *
Comment: The concept of "letters" here is characters a-z, A-Z, and other characters with ASCII codes from 127 to 255 (0x7f-0xff).
Syntax
You can define a constant using the define() function or using keyword const outside the class declaration since PHP 5.3.0. Once a constant is defined, its value cannot be changed or invalidated.
Constants can only contain scalar data (boolean, integer, float and string types). It is also possible to define constants of type , but this should be avoided as it may lead to unexpected results.
You can get the value of a constant by specifying its name. Unlike variables, you no need precede the constant name with a symbol $ . You can also use the constant() function to get the value of a constant if you are generating the constant name dynamically. Use the get_defined_constants() function to get a list of all declared constants.
Comment: Constants and (global) variables are in different namespaces. This means that, for example, TRUE and $TRUE are completely different things.
If you use an undefined constant, PHP assumes that you mean the constant's name, as if you had specified a string literal (CONSTANT instead of "CONSTANT"). This will generate an E_NOTICE level error. See also the manual chapter which explains why $foo is wrong (unless you have declared it first, of course). bar as a constant using define()). If you just want to check if a constant is defined, use the defined() function.
Differences between constants and variables:
- Constants do not have a dollar sign prefix ( $ );
- Constants can only be defined using the define() function, not by assigning a value;
- Constants can be defined and accessed anywhere without regard to scope;
- Constants cannot be redefined or invalidated after their initial declaration; And
- Constants can only have scalar values.
"Magic" constants
PHP provides a large list of predefined constants for every script you run. 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 seven 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. Special constants are case insensitive and are listed below:
Name | Description |
---|---|
__LINE__ | The current line number in the file. |
__FILE__ | Full path and name of the current file. If used inside an included file, the name of this file is returned. Since PHP version 4.0.2, __FILE__ always contains an absolute path with symlinks allowed, whereas older versions would return a relative path in some circumstances. |
__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 in a slash, with the exception of the root directory (added in PHP 5.3.0.) |
__FUNCTION__ | Function name. (Added in PHP 4.3.0.) Since PHP 5, this constant returns the function name exactly as it was declared (case sensitive). In PHP 4 this value was always lowercase. |
__CLASS__ | Class name. (Added in PHP 4.3.0) Since PHP 5, this constant returns the class name exactly as it was declared (case sensitive). In PHP 4 this value was always lowercase. The class name contains the name of the namespace in which the class was declared (for example, Foo\Bar). Please note that since PHP5.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. (Added in PHP 5.4.0) Since PHP 5.4, this constant returns the trait name exactly as it was declared (case sensitive). This name contains the namespace in which the trait was declared (for example, Foo\Bar). |
__METHOD__ | The name of the class method. (Added in PHP 5.0.0) The method name is returned as it was declared (case sensitive). |
__NAMESPACE__ | The name of the current namespace (case sensitive). This constant is determined at compile time (Added in PHP 5.3.0). |
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 that // will break your script define("__FOO__", "something");» 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.
In this note we will talk about constants. As usual, let's look at the very concept of constants in programming languages and see how they are declared and used constants in PHP.
The concept of constant and constants in PHP
The word constant should already be familiar to you from mathematics:
“Mathematical constant- a quantity whose value does not change.”
It's the same in PHP. Constant in PHP is an identifier that serves to designate a simple value (string, some number) that cannot change during code execution.
To declare a constant (assign a value to it), use the function define. Example of a constant declaration:
Constant names in PHP are case sensitive (uppercase and lowercase letters are different), so you need to be careful. There is also a convention that constant names are always written in upper case.
The constant name must begin with a letter or underscore “_” and can consist of letters, numbers, and underscores.
Let's look at a simple example of using a constant:
In this example, we declared a constant and used it in the program.
What are constants used for and isn't it easier to use variables?
As already mentioned, constants cannot change their values during program execution. Constants usually store permanent site parameters, such as database access details (host, user login and password, database name), site location on disk, and many other settings.
If we use variables, the script may accidentally (in case of an error) change the value of the variable and will not work as you intended.
Using constants ensures that the value you specify when declaring the constant remains unchanged.
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 the boolean value 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 full path and the 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