Home  >  Article  >  Backend Development  >  How to define constants, system constants and use constants in PHP

How to define constants, system constants and use constants in PHP

伊谢尔伦
伊谢尔伦Original
2017-06-29 10:24:244303browse

Constant in PHP is divided into custom constants and system constants. Custom constants need to be defined using PHP functions. System constants can be used directly. See below. Let’s look at the differences in the use of these two constants

1. Custom constants

* Must be defined using the function define()
* After definition The value cannot be changed anymore
* Use the constant name directly when using it. You cannot add $s in front like a variable
For example: define("PI",3.14); Define a constant
$area = PI* R*R; Calculate the area of ​​a circle
define("URL","http://www.php.cn");
echo "My URL is:".URL;

2 System constants:

FILE: PHP program file name
LINE: PHP program file line number
PHP_VERSION: The version number of the current parser
PHP_OS: Execute the current The operating system name of the PHP version
can be used directly. For example, if you want to view the name of the operating system running the current PHP version, you can write echo PHP_OS

php defines and uses a class constant

php class constants

We can define constants in classes. The value of a constant will always remain the same. There is no need to use the $ symbol when defining and using constants.

The value of a constant must be a fixed value and cannot be the result of a variable, class attribute or other operation (such as a function call).

Its also possible for interfaces to have constants. Look at the interface documentation for examples. Constants can also be defined in interfaces. See the interface's documentation for more examples.

After PHP5.3.0, we can use a variable to dynamically call the class. But the value of this variable cannot be the keywords self, parent or static.

Define and use a class constant

<?php
class MyClass
{
const constant = ‘constant value&#39;;
function showConstant() {
echo self::constant . “\n”;
}
}
echo MyClass::constant . “\n”;
$classname = “MyClass”;
echo $classname::constant . “\n”; // PHP 5.3.0之后
$class = new MyClass();
$class->showConstant();
echo $class::constant.”\n”; // PHP 5.3.0之后
?>

Example #2 staticData example

<?php
class foo {
// PHP 5.3.0之后
const bar = <<<&#39;EOT&#39;
bar
EOT;
}
?>


The above is the detailed content of How to define constants, system constants and use constants in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn