Constants in PHP and how to declare constants
- 28-07-2022
- Toanngo92
- 0 Comments
Mục lục
The concept of constants
A constant is a term that identifies a single value. The value of the constant cannot be changed while the script is running. Constant names can only begin with a letter or an underscore (the $ sign cannot be placed before the constant name).
Constants, unlike variables, are automatically global throughout the script. In short, a constant is similar to a variable, but once specified, it cannot be changed
Definition of constant
Syntax Initializing constants in PHP:
define(name, value, case-insensitive)
For example:
<?php define('VERSION','8.0'); echo VERSION; // output: 8.0 ?>
Constant Array
In PHP 8, an array constant can be created using the define() function.
<?php define("CARS", [ "Alfa Romeo", "BMH", "Toyota", "Range-Rover" ]); var_dump(CARS); // array(4) { [0]=> string(10) "Alfa Romeo" [1]=> string(3) "BMH" [2]=> string(6) "Toyota" [3]=> string(11) "Range-Rover" }
Constants exist on the global scope. Therefore, they can be used throughout the script.
Example using constants inside the function, even though they are defined outside the function:
<?php define("Hello", "what's new in PHP?"); function myTest() { echo Hello; } myTest(); //output: what's new in PHP? ?>
Magic Constants in PHP (predefined constants)
In PHP, the value of some predefined constants changes depending on the context in which they are used. These constants are called Magic Constants. They are not case sensitive. There are nine magic constants in PHP, eight of which start and end with a double underscore (__):
- __LINE__
- __FILE__
- __DIR__
- __FUNCTION__
- __CLASS__
- __TRAIT__
- __METHOD__
- __NAMESPACE__
- ClassName::class
Constant Names | description |
__LINE__ | Returns the current line number |
__FILE__ | Returns the absolute path of the current file |
__DIR__ | Returns the current directory path |
__FUNCTION__ | Returns the current function being called |
__CLASS__ | Returns the current Class |
__TRAIT__ | Returns the TRAIT in use |
__METHOD__ | Returns the current method |
__NAMESPACE__ | Returns the current namespace |
ClassName::class | Returns the current class |
Unlike regular constants, all 9 of these constants are resolved at compile time instead of run time.