Home > Article > Backend Development > Use 3 magic constants in PHP to quickly get directory, file name and line number
In the previous article " Still can't tell the difference between fgets, fgetss and fgetcsv in PHP? Collect quickly! 》Introduces you to the different uses of fgets, fgetss and fgetcsv in PHP. Friends in need can learn about it~
The main content of this article is to introduce how to use three magical functions in PHP Constants to quickly get the current directory, file name and line number!
Everyone should know that PHP provides a large number of "magic" constants, and these constants are case-sensitive. With the help of these constants, we can get the current directory, file name, current line number, etc. These constants are safe, reliable, and fast, which is why web developers prefer using PHP! PHP yyds haha!
Getting back to the subject, let me introduce to you how to use PHP constants to obtain the current directory, file name and code line number!
1. Get the current directory
__DIR__
: This constant is used to get the current directory of the file, which is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. If used within an include method, returns the directory containing the file.
<?php echo "此文件的当前目录为 '" . __DIR__ . "'.<br>"; ?>
The output result is:
此文件的当前目录为 'D:\wamp\www'.
2. Get the current file name with the complete file path
__FILE__
: This is used to return the full file path and file name of the file. If used within an include method, returns the name of the included file.
<?php echo "当前文件的路径为 '" . __FILE__ . "'.\n"; ?>
Output:
当前带有路径的文件是 'D:\wamp\www\test.php'.
Note: This magic constant is mainly used when some files in the directory must be included.
3. Get the current line number
__LINE__
: This is used to return the current line number of the file.
<?php echo "这段代码的行号是 '" . __LINE__ . "'.\n"; ?>
The output result is:
这段代码的行号是 '2'.
As shown in the figure:
Note: This constant is mainly used for debugging code, or getting errors Line number.
PHP Chinese website platform has a lot of video teaching resources. Welcome everyone to learn "PHP Video Tutorial"!
The above is the detailed content of Use 3 magic constants in PHP to quickly get directory, file name and line number. For more information, please follow other related articles on the PHP Chinese website!