PHP magic constant like __CLASS__, __TRAIT__, __METHOD__, __NAMESPACE__
php code for magic constant
Example :
<?php
namespace PHPCODE;
echo "Printing at line number " . __LINE__ . "<br>";
?>
<?php
echo "Print full path of file : ".__FILE__ . "<br>";
?>
<?php
echo "Print full path of directory : ".__DIR__ . "<br>";
?>
<?php
//Using magic constant inside function.
function get_func(){
echo 'The function name is '. __FUNCTION__ . "<br>";
}
get_func();
?>
<?php
//Get Class name using magic constant __CLASS__
class ARYATECHNO
{
public function __construct() { }
function getClassName(){
echo "Class name is ".__CLASS__ . "<br>";
}
}
$obj = new ARYATECHNO;
$obj->getClassName();
?>
<?php
//prints name of the trait
trait get_Trait {
function print_trait(){
echo "Name of the trait :".__TRAIT__. "<br>";
}
}
class ARYATECH {
use get_Trait;
}
$obj = new ARYATECH;
$obj->print_trait();
?>
<?php
//Get method name using magic constants
class MAGIC {
public function __construct() {
echo "Method name is ".__METHOD__ . "<br>";
}
public function get_method(){
echo "Method name is ".__METHOD__."<br>";
}
}
$obj = new MAGIC;
$obj->get_method();
?>
<?php
//Get namespace name using magic constants
class package {
public function __construct() {
echo 'Namespace name is '.__NAMESPACE__."<br>";
}
}
$obj = new package;
?>
<?php
class CLASSA {
}
echo "Get class name : ".CLASSA::class."<br>";
?>
Output :
Comments