Home >Backend Development >PHP Tutorial >PHP study notes_4_Points to note about constants and magic constants
Constants correspond to variables in php. Constants are sub-system constants, framework constants, and custom constants
To define constants, you can use the following
<code><span><span><?php</span> define(<span>"MY_FIELD"</span>,<span>123</span>); <span>echo</span> MY_FIELD;<span>// 输出123</span><span>// 如果定义常量是一个变量</span><span>$name</span> = <span>"TEST"</span>; define(<span>$name</span>,<span>"456"</span>); <span>echo</span><span>$name</span>;<span>// 输出TEST</span><span>echo</span> constant(<span>$name</span>);<span>//输出真正的变量值456</span><span>?></span></span></code>
Notes:
1. Use it directly without adding the '$' sign;
2. Constants can be defined and used anywhere;
3. You can use the constant name or constant (constant name) function to get the value of the constant;
4.get_defined_constants(); can obtain all defined constants;
Magic constants: added by different extension libraries. Commonly used magic constants are as follows:
Name | Description |
---|---|
__LINE__
|
The current line number in the file. |
__DIR__ |
The directory where the current file is located. |
__FILE__ |
The full path and file name of the file. If used in an include file, returns the include file name. Since PHP 4.0.2, FILE always contains an absolute path, while versions before that sometimes contained a relative path. |
__FUNCTION__ |
Function name (newly added in php 4.3.0). Since PHP 5 this constant returns the name of the function when it was defined (case sensitive). In php 4 the value is always lower case. |
__CLASS__ |
The name of the class (new in php 4.3.0). Since PHP 5 this constant returns the name of the class when it was defined (case sensitive). In php 4 the value is always lower case. |
__METHOD__ |
The method name of the class (newly added in php 5.0.0). Returns the name of the method when it was defined (case-sensitive). |
__NAMESPACE__ |
The name of the current namespace (case sensitive). This constant is defined at compile time (new in PHP 5.3.0) |
Copyright statement: This article is an original article. Reprints must indicate the source. The views in the article only represent the views at the time. There must be shortcomings. Welcome Thank you very much for the reminder!
The above introduces the points that need to be paid attention to in PHP study notes_4_constants and magic constants, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.