How to define and use constants in PHP_PHP Tutorial

WBOY
Release: 2016-07-21 15:13:04
Original
1253 people have browsed it

1. Custom constants

* Must be defined using the function define()
* After definition, its value cannot be changed
* When used, use the constant name directly, and 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 ​​the circle
define("URL", "http://www.jb51.net");
echo "My URL is: ".URL;

2 System constants:

FILE: PHP program file name
LINE: PHP program file line number
PHP_VERSION: version number of the current parser
PHP_OS: name of the operating system that executes the current PHP version
can be obtained directly Use, for example, 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 a class. But the value of this variable cannot be the keywords self, parent or static.

Define and use a class constant

Copy the code The code is as follows:

class MyClass
{
const constant = 'constant value';
function showConstant() {
echo self::constant . “n”;
}
}

echo MyClass::constant . “n”;

$classname = “MyClass”;
echo $classname::constant . “n”; // After PHP 5.3.0

$class = new MyClass();
$class->showConstant();

echo $class::constant.”n”; // After PHP 5.3.0
?>

Example #2 Static data example

Copy code The code is as follows:

class foo {
// PHP 5.3. After 0
const bar = <<<'EOT'
bar
EOT;
}
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/326559.htmlTechArticle1. Custom constants* must be defined using the function define()* and their values ​​cannot be changed after definition* When using it, use the constant name directly. You cannot add $s in front like a variable. For example: define("PI",3....
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template