Magic constants are special built-in constants whose value depends on where in your code you use them. They start and end with two underscores.
| Constant | Gives you |
|---|---|
__LINE__ | The current line number |
__FILE__ | The full path of the current file |
__DIR__ | The folder of the current file |
__FUNCTION__ | The name of the current function |
__CLASS__ | The name of the current class |
__METHOD__ | The class and method name |
__NAMESPACE__ | The current namespace |
Example
<?php
function showWhere(): void
{
echo "Function: " . __FUNCTION__ . "\n";
echo "Line: " . __LINE__ . "\n";
}
showWhere();
echo "File name: " . basename(__FILE__);
Function: showWhere
Line: 5
File name: index.php
The one you will use most: __DIR__
When you include another file, a path like "config.php" depends on where the script was started. __DIR__ always gives a path that is relative to the current file, so it never breaks.
<?php
require __DIR__ . "/config.php";
You will use this a lot in Include and Require.
In classes
<?php
class Report
{
public function title(): string
{
return __CLASS__ . " / " . __METHOD__;
}
}
echo (new Report())->title();
Report / Report::title
Logging is a good use
"Failed in " . __METHOD__ . " line " . __LINE__ tells you exactly where the problem happened.