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:

  1. Regular (set by the programmer)
  2. 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:

Some "magic" PHP constants
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?

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 PHP arrays 8.3 PHP array() function 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 Converting 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 Examples regular expressions 15.8 Conclusion to Chapter 15 16.1 Working with Cookies in PHP 16.2 Creating Cookies in PHP 16.3 Reading from Cookies 16.4 Removing 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.

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


Close