English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this tutorial, you will learn how to use PHP magic constants.
InPHP ConstantsIn this chapter, we learned how to define and use constants in PHP scripts.
In addition, PHP provides a set of special predefined constants that change according to the position where they are used. These constants are called magic constants. For example, the value of __line__ depends on the line in the script where it is used.
Magic constants start with two underscores and end with two underscores. The following part describes some of the most useful PHP magic constants.
__LINE__ constant returns the current line number of the file, as shown below:
<?php echo "Line number " . __LINE__ . "<br>"; // Output: Line number 2 echo "Line number " . __LINE__ . "<br>"; // Output: Line number 3 echo "Line number " . __LINE__ . "<br>"; // Output: Line number 4 ?>test and see‹/›
__FILE__ constant returns the full path and name of the currently executing PHP file. If used inincludeIf used in
<?php //Show the absolute path of this file echo "The full path of this file is: " . __FILE__; ?>test and see‹/›
__DIR__ constant returns the directory of the file. If used in include, it returns the directory of the included file. Here is an example:
<?php // Show the directory of this file echo "The directory of this file is: " . __DIR__; ?>test and see‹/›
__FUNCTION__ constant returns the name of the current function.
<?php function myFunction(){ echo "The function name is - " . __FUNCTION__; } myFunction(); // Output: The function name is - myFunction ?>test and see‹/›
__CLASS__ constant returns the currentclassThe name. Here is an instance of:
<?php class MyClass { public function getClassName(){ return __CLASS__; } } $obj = new MyClass(); echo $obj->getClassName(); // Output: MyClass ?>test and see‹/›
__METHOD__ constant returns the name of the current class method.
<?php class Sample { public function myMethod(){ echo __METHOD__; } } $obj = new Sample(); $obj->myMethod(); // Output: Sample::myMethod ?>test and see‹/›
__NAMESPACE__ constant returns the name of the current namespace.
<?php namespace MyNamespace; class MyClass { public function getNamespace(){ return __NAMESPACE__; } } $obj = new MyClass(); echo $obj->getNamespace(); // Output: MyNamespace ?>test and see‹/›