How do you define and use constants in PHP

  • 2020-05-30 19:45:03
  • OfStack

1. Customize constants

* must be defined by the function define()
The value cannot be changed after the definition
* use the name of a constant directly, instead of $s in front of it like variable 1
For example: define (" PI ", 3.14); Define 1 constant
$area = R PI * * R; Calculate the area of the circle
define("URL","https://www.ofstack.com");
echo "my website is: ".URL;

2 system constants:

FILE :php program file name
LINE: line number of PHP program files
PHP_VERSION: the version number of the current parser
PHP_OS: executes the operating system name of the current version of PHP
You can use it directly. For example, to see the operating system name for the current version of PHP, you can write echo PHP_OS

php defines and USES one class constant

php class constant

We can define constants in a class. The value of the constant will always remain the same. You do not need to use the $sign when defining and using constants.

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

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

After PHP 5.3.0, we can call the class dynamically with a variable. However, the value of this variable cannot be the keyword self, parent, or static.

Define and use 1 class constant


<?php
class MyClass
{
const constant =  ' constant value';
function showConstant() {
echo self::constant .  " \n " ;
}
}
echo MyClass::constant .  " \n " ;
$classname =  " MyClass " ;
echo $classname::constant .  " \n " ; // PHP 5.3.0 after 
$class = new MyClass();
$class->showConstant();
echo $class::constant. " \n " ; // PHP 5.3.0 after 
?>

Example #2 static data example


<?php
class foo {
// PHP 5.3.0 after 
const bar = <<<'EOT'
bar
EOT;
}
?>


Related articles: