search
HomeBackend DevelopmentPHP TutorialPHP中的_FILE,CLASS等戏法变量

PHP中的__FILE,__CLASS等魔术变量

今天看到一个魔术变量,是以前没见过的,__DIR__,我查了查,发现原来是php5.3新增的,顺便举几个例子,解释一下php的魔术变量

1,__FILE__

文件的完整路径和文件名。如果用在被包含文件中,则返回被包含的文件名。自 PHP 4.0.2 起,__FILE__ 总是包含一个绝对路径(如果是符号连接,则是解析后的绝对路径),而在此之前的版本有时会包含一个相对路径。
这个变量,我用的是最多的,估计也是大家用的最多的。

web服务器都会指定一个documentroot的,但是不同的服务器,设置的documentroot有可能是不同的,在这种情况下,把一个网站从一个服务器搬家到另一个服务器,这样就有可能因为路径的不同,造成网站跑不起来。

  1. /** ?
  2. 在你的公用的配置文件中,来设置你的根目录,这样就不用担心经常搬家了。 ?
  3. */??
  4. define('ROOT_PATH',?dirname(__FILE__)?.?DIRECTORY_SEPARATOR); ??
  5. echo?ROOT_PATH; ??
  6. echo?"
    "
    ; ??
  7. echo?__FILE__; ??
  8. echo?"
    "
    ; ??
  9. echo?dirname(__FILE__); ??
  10. echo?"
    "
    ; ??
  11. echo?dirname(dirname(__FILE__)); ??
  12. ?>??
<?php /**在你的公用的配置文件中,来设置你的根目录,这样就不用担心经常搬家了。*/define('ROOT_PATH', dirname(__FILE__) . DIRECTORY_SEPARATOR);echo ROOT_PATH;echo "<br>";echo __FILE__;echo "<br>";echo dirname(__FILE__);echo "<br>";echo dirname(dirname(__FILE__));?>

2,__LINE__

文件中的当前行号。这个变量在调试错误的时候,还是比较有作用的,其他的时候,没什么用处,纯属个人观点。

  1. echo?__LINE__;??//显示,__LINE__所在的行号 ??
  2. ?>??
<?phpecho __LINE__;  //显示,__LINE__所在的行号?>

3,__CLASS__

类的名称,PHP5返回的结果是区分大小写的

  1. class?base_class ??
  2. { ??
  3. ?function?say_a() ??
  4. ?{ ??
  5. ?echo?"'a'?-?said?the?"?.?__CLASS__?.?"
    "
    ; ??
  6. ?} ??
  7. ?function?say_b() ??
  8. ?{ ??
  9. ?echo?"'b'?-?said?the?"?.?get_class($this)?.?"
    "
    ; ??
  10. ?} ??
  11. } ??
  12. ??
  13. class?derived_class?extends?base_class ??
  14. { ??
  15. ?function?say_a() ??
  16. ?{ ??
  17. ?parent::say_a(); ??
  18. ?echo?"'a'?-?said?the?"?.?__CLASS__?.?"
    "
    ; ??
  19. ?} ??
  20. ?function?say_b() ??
  21. ?{ ??
  22. ?parent::say_b(); ??
  23. ?echo?"'b'?-?said?the?"?.?get_class($this)?.?"
    "
    ; ??
  24. ?} ??
  25. } ??
  26. ??
  27. $obj_b?=?new?derived_class(); ??
  28. $obj_b->say_a(); ??
  29. echo?"
    "
    ; ??
  30. $obj_b->say_b(); ??
  31. ?> ??
  32. 结果为: ??
  33. 'a'?-?said?the?base_class ??
  34. 'a'?-?said?the?derived_class ??
  35. ??
  36. 'b'?-?said?the??derived_class ??
  37. 'b'?-?said?the?derived_class??
<?phpclass base_class{ function say_a() { echo "'a' - said the " . __CLASS__ . "<br/>"; } function say_b() { echo "'b' - said the " . get_class($this) . "<br>"; }}class derived_class extends base_class{ function say_a() { parent::say_a(); echo "'a' - said the " . __CLASS__ . "<br>"; } function say_b() { parent::say_b(); echo "'b' - said the " . get_class($this) . "<br>"; }}$obj_b = new derived_class();$obj_b->say_a();echo "<br>";$obj_b->say_b();?>结果为:'a' - said the base_class'a' - said the derived_class'b' - said the  derived_class'b' - said the derived_class

有的时候,我们可以用get_class来代替__CLASS__

4,__FUNCTION__和__METHOD__

__FUNCTION__:函数名称,php5中返回的结果是区分大小写的
__METHOD__:方法中的函数名称,php5中返回的结果是区分大小写的

二个都是取得方法的名称,有什么不同呢?

  1. class?test ??
  2. { ??
  3. ?function?a() ??
  4. ?{ ??
  5. ?echo?__FUNCTION__; ??
  6. ?echo?"
    "
    ; ??
  7. ?echo?__METHOD__; ??
  8. ?} ??
  9. } ??
  10. ??
  11. function?good?(){ ??
  12. ?echo?__FUNCTION__; ??
  13. ?echo?"
    "
    ; ??
  14. ?echo?__METHOD__; ??
  15. } ??
  16. ??
  17. $test?=?new?test(); ??
  18. $test->a(); ??
  19. echo?"
    "
    ; ??
  20. good(); ??
  21. ?> ??
  22. 返回结果: ??
  23. a ??
  24. test::a ??
  25. good ??
  26. good??
<?phpclass test{ function a() { echo __FUNCTION__; echo "<br>"; echo __METHOD__; }}function good (){ echo __FUNCTION__; echo "<br>"; echo __METHOD__;}$test = new test();$test->a();echo "<br>";good();?>返回结果:atest::agoodgood

相对于孤立的函数来说,二个都可以取出函数名,没什么区别,如果是class中的方法时,__FUNCTION__只能取出class的方法名,而__METHOD__不光能取出方法名,还能取出class名

5,__DIR__

文件所在的目录。如果用在被包括文件中,则返回被包括的文件所在的目录。它等价于 dirname(__FILE__)。除非是根目录,否则目录中名不包括末尾的斜杠。(PHP 5.3.0中新增)

如果在5.3以前的版本中想用__DIR__的话,可以这样

  1. if(!defined('__DIR__'))?{ ??
  2. ?$iPos?=?strrpos(__FILE__,?"/"); ??
  3. ?define("__DIR__",?substr(__FILE__,?0,?$iPos)?.?"/"); ??
  4. } ??
  5. ?>??
<?phpif (!defined('__DIR__')) { $iPos = strrpos(__FILE__, "/"); define("__DIR__", substr(__FILE__, 0, $iPos) . "/");}?>

6,__NAMESPACE__

当前命名空间的名称(大小写敏感)。这个常量是在编译时定义的(PHP 5.3.0 新增)

7,__STATIC__

当你调用class的静态方法时,返回class名称,区分大小写。如果在继承中调用的话,不管在继承中有没有定义,都能返回继承的class名。

  1. //php5.3 ??
  2. class?Model ??
  3. { ??
  4. ?public?static?function?find() ??
  5. ?{ ??
  6. ?echo?__STATIC__; ??
  7. ?} ??
  8. } ??
  9. ??
  10. class?Product?extends?Model?{} ??
  11. class?User?extends?Model?{} ??
  12. ??
  13. Product::find();?//?"Product" ??
  14. User::find();?//?"User" ??
  15. ?>??
<?php //php5.3class Model{ public static function find() { echo __STATIC__; }}class Product extends Model {}class User extends Model {}Product::find(); // "Product"User::find(); // "User"?>
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
What are the advantages of using a database to store sessions?What are the advantages of using a database to store sessions?Apr 24, 2025 am 12:16 AM

The main advantages of using database storage sessions include persistence, scalability, and security. 1. Persistence: Even if the server restarts, the session data can remain unchanged. 2. Scalability: Applicable to distributed systems, ensuring that session data is synchronized between multiple servers. 3. Security: The database provides encrypted storage to protect sensitive information.

How do you implement custom session handling in PHP?How do you implement custom session handling in PHP?Apr 24, 2025 am 12:16 AM

Implementing custom session processing in PHP can be done by implementing the SessionHandlerInterface interface. The specific steps include: 1) Creating a class that implements SessionHandlerInterface, such as CustomSessionHandler; 2) Rewriting methods in the interface (such as open, close, read, write, destroy, gc) to define the life cycle and storage method of session data; 3) Register a custom session processor in a PHP script and start the session. This allows data to be stored in media such as MySQL and Redis to improve performance, security and scalability.

What is a session ID?What is a session ID?Apr 24, 2025 am 12:13 AM

SessionID is a mechanism used in web applications to track user session status. 1. It is a randomly generated string used to maintain user's identity information during multiple interactions between the user and the server. 2. The server generates and sends it to the client through cookies or URL parameters to help identify and associate these requests in multiple requests of the user. 3. Generation usually uses random algorithms to ensure uniqueness and unpredictability. 4. In actual development, in-memory databases such as Redis can be used to store session data to improve performance and security.

How do you handle sessions in a stateless environment (e.g., API)?How do you handle sessions in a stateless environment (e.g., API)?Apr 24, 2025 am 12:12 AM

Managing sessions in stateless environments such as APIs can be achieved by using JWT or cookies. 1. JWT is suitable for statelessness and scalability, but it is large in size when it comes to big data. 2.Cookies are more traditional and easy to implement, but they need to be configured with caution to ensure security.

How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?How can you protect against Cross-Site Scripting (XSS) attacks related to sessions?Apr 23, 2025 am 12:16 AM

To protect the application from session-related XSS attacks, the following measures are required: 1. Set the HttpOnly and Secure flags to protect the session cookies. 2. Export codes for all user inputs. 3. Implement content security policy (CSP) to limit script sources. Through these policies, session-related XSS attacks can be effectively protected and user data can be ensured.

How can you optimize PHP session performance?How can you optimize PHP session performance?Apr 23, 2025 am 12:13 AM

Methods to optimize PHP session performance include: 1. Delay session start, 2. Use database to store sessions, 3. Compress session data, 4. Manage session life cycle, and 5. Implement session sharing. These strategies can significantly improve the efficiency of applications in high concurrency environments.

What is the session.gc_maxlifetime configuration setting?What is the session.gc_maxlifetime configuration setting?Apr 23, 2025 am 12:10 AM

Thesession.gc_maxlifetimesettinginPHPdeterminesthelifespanofsessiondata,setinseconds.1)It'sconfiguredinphp.iniorviaini_set().2)Abalanceisneededtoavoidperformanceissuesandunexpectedlogouts.3)PHP'sgarbagecollectionisprobabilistic,influencedbygc_probabi

How do you configure the session name in PHP?How do you configure the session name in PHP?Apr 23, 2025 am 12:08 AM

In PHP, you can use the session_name() function to configure the session name. The specific steps are as follows: 1. Use the session_name() function to set the session name, such as session_name("my_session"). 2. After setting the session name, call session_start() to start the session. Configuring session names can avoid session data conflicts between multiple applications and enhance security, but pay attention to the uniqueness, security, length and setting timing of session names.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!