Home  >  Article  >  Backend Development  >  Detailed explanation of magic constants in PHP

Detailed explanation of magic constants in PHP

autoload
autoloadOriginal
2021-04-19 12:43:592601browse

Detailed explanation of magic constants in PHP

Constant is an identifier (name) of a simple value. Once constant is defined, it is not allowed to be changed, but everything has Exception, PHP has built-in Magic Constants, which will produce different values ​​as the position changes. This article will take you to learn about the Magic Constants in PHP.

1.__LINE__

<?php

echo __LINE__."<br>";//3

echo __LINE__."<br>";//5

?>

The current line number in the file.​

2.__FILE__

<?php
        echo __FILE__."<br>";//F:\learnlog\zend\php\magic.php
?>

The full path and file name of the file. If used in an included file, returns the included file name

##3.__DIR__##

<?php
        echo __DIR__."<br>";//F:\learnlog\zend\php
?>

The directory where the file is located . If used within an included file, returns the directory where the included file is located.​

4.__METHOD__

<?php
function sum(){
    echo __METHOD__."<br>";
}
sum();//输出:sum
?>

The name of the current function.

5.__CLASS__

<?php
class People{
  
  static function sum(){
     echo __CLASS__;
  }
}
People::sum();//People
?>
The name of the current class.

6.__NAMESPACE__

<?php
namespace Controller;
class People{
  
  static function sum(){
     echo __NAMESPACE__;
  }
}
People::sum();//Controller
?>

The name of the current namespace

7. __TRAIT__

<?php
trait A{
     function traitName() 
     {echo __TRAIT__;}
 }
 trait B {
     use A;
 }
 class Test {
     use B;
 }
 (new Test)->traitName(); //A
?>
Trait’s name

Recommendation:

2021 PHP interview questions summary (collection)》《 php video tutorial

The above is the detailed content of Detailed explanation of magic constants in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn