☰ See All Chapters |
PHP Magic Constants
PHP magic constants change their behavior based on the place where they are used. Constants do magic for you and supply you the behavior according to the place of usage.
__LINE__
The __LINE__ constant returns the current line number of the file.
<?php echo "Line number " . __LINE__ . "<br>"; echo "Line number " . __LINE__ . "<br>"; echo "Line number " . __LINE__ . "<br>"; ?> |
__FUNCTION__
__FUNCTION__ returns the name of the function.
<?php
class Demo { public function hello() { echo __FUNCTION__; } } $obj = new Demo(); $obj->hello(); ?> |
__METHOD__
__METHOD__ returns the name of the class along with the name of the function.
<?php
class Demo { public function hi() { echo __METHOD__; } } $obj = new Demo(); $obj->hi(); ?> |
__CLASS__
__CLASS__ magic constant returns the name of the class where it was defined (i.e. where you wrote the function call/constant name).
get_class() function behaves same way as __CLASS__ magic constant when called without parameters. In contrast, get_class($this) and get_called_class() functions call, will both return the name of the actual class which was instantiated.
<?php class Super_Class { public function say(){ echo '__CLASS__ value: ' . __CLASS__ . "</br>"; echo 'get_called_class() value: ' . get_called_class() . "</br>"; echo 'get_class($this) value: ' . get_class($this) . "</br>"; echo 'get_class() value: ' . get_class() . "</br>"; } } class Sub_Class extends Super_Class {} $c = new Sub_Class(); $c->say(); ?> |
__FILE__
You can get the name of the current PHP file (with the absolute path) using the __FILE__ magic constant. This is most often used as a logging/debugging technique.
<?php echo "The full path of this file is: " . __FILE__; ?> |
__DIR__
__DIR__ magic constant is used to get the absolute path to the directory where the current file is located. While framing the directory path, you should use directory separator / on *nix, and \ on Windows. So if you are not sure about the operating system, you can use DIRECTORY_SEPARATOR constant for separating directories in a path which takes value / on *nix, and \ on Windows.
<?php echo "The directory of this file is: " . __DIR__ ."</br>"; $view = 'page'; $viewFile = __DIR__ . DIRECTORY_SEPARATOR .'views' . DIRECTORY_SEPARATOR . $view; echo $viewFile; ?> |
All Chapters