Lecture
There are cases when variables are rather inconvenient to use for permanent storage of any specific values that do not change during the program operation. Such values can be mathematical constants, paths to files, various passwords, etc. For this purpose, PHP provides for such a construction as constant .
Constant called a named quantity that does not change during the execution of the program (script).
Unlike variables, you cannot change the values of the constants that were assigned to them when they were declared. Constants are useful for storing values that should not be changed while the program is running. Constants can contain only scalar data (of logical, integer, floating, and string types).
In PHP, constants are defined by the define () function. This function has the following format:
define ( $name , $value , $case_sen ), где:
$name - имя константы;
$value - значение константы;
$case_sen - необязательный параметр логического типа,
указывающий, следует ли учитывать регистр букв (true) или нет (false).
An example of defining and using constants in PHP:
<? php
define ( "pi" , 3.14 , true );
echo pi ;
// Выводит 3.14
?>
If the $ case_sen parameter is true , the interpreter will be case sensitive when working with a constant. Note that constants are used without the leading $ sign.
Differences between constants and variables:
Constants do not have a prefix in the form of a dollar sign ( $ );
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 defined or canceled after the initial declaration;
Constants can only have scalar values.
Check for the existence of constants
To test for the existence of a constant, you can use the defined () function. This function returns true if the constant is declared. Let's give an example:
<? php
// Объявляем константу pi
define ( "pi" , 3.14 , true );
if ( defined ( "pi" )== true ) echo "Константа pi объявлена!" ;
// Скрипт выведет 'Константа pi объявлена!'
?>
PHP Predefined Constants
In PHP, there are the following predefined constants:
PHP provides a large list of predefined constants for each executed script. Many of these constants are defined by different modules and will only be present if these modules are available as a result of dynamic loading or as a result of static assembly.
There are five predefined constants that change their value depending on the context in which they are used. For example, the constant __LINE__ depends on the string in the script on which this constant is specified. Special constants are case insensitive and a list of them is given below:
Comments
To leave a comment
Running server side scripts using PHP as an example (LAMP)
Terms: Running server side scripts using PHP as an example (LAMP)