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

Detailed explanation of magic constants in PHP

autoload
Release: 2023-04-09 21:26:02
Original
2635 people have browsed it

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

?>
Copy after login

The current line number in the file.​

2.__FILE__

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

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
?>
Copy after login

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
?>
Copy after login

The name of the current function.

5.__CLASS__

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

6.__NAMESPACE__

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

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
?>
Copy after login
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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template