PHP中魔术方法和魔术常量使用总结
魔术方法(Magic methods)
PHP中把以两个下划线__开头的方法称为魔术方法,这些方法在PHP中充当了举足轻重的作用。 魔术方法包括:
-
__construct(),类的构造函数
-
__destruct(),类的析构函数
-
__call(),在对象中调用一个不可访问方法时调用
-
__callStatic(),用静态方式中调用一个不可访问方法时调用
-
__get(),获得一个类的成员变量时调用
-
__set(),设置一个类的成员变量时调用
-
__isset(),当对不可访问属性调用isset()或empty()时调用
-
__unset(),当对不可访问属性调用unset()时被调用。
-
__sleep(),执行serialize()时,先会调用这个函数
-
__wakeup(),执行unserialize()时,先会调用这个函数
-
__toString(),类被当成字符串时的回应方法
-
__invoke(),调用函数的方式调用一个对象时的回应方法
-
__set_state(),调用var_export()导出类时,此静态方法会被调用。
-
__clone(),当对象复制完成时调用
__construct()和__destruct()
构造函数和析构函数应该不陌生,他们在对象创建和消亡时被调用。例如我们需要打开一个文件,在对象创建时打开,对象消亡时关闭
class FileRead { protected $handle = NULL; function __construct(){ $this->handle = fopen(...); } function __destruct(){ fclose($this->handle); } } ?>
这两个方法在继承时可以扩展,例如:
class TmpFileRead extends FileRead { function __construct(){ parent::__construct(); } function __destruct(){ parent::__destruct(); } } ?>
__call()和__callStatic()
在对象中调用一个不可访问方法时会调用这两个方法,后者为静态方法。这两个方法我们在可变方法(Variable functions)调用中可能会用到。
class MethodTest { public function __call ($name, $arguments) { echo "Calling object method '$name' ". implode(', ', $arguments). "\n"; } public static function __callStatic ($name, $arguments) { echo "Calling static method '$name' ". implode(', ', $arguments). "\n"; } } $obj = new MethodTest; $obj->runTest('in object context'); MethodTest::runTest('in static context'); ?>
__get(),__set(),__isset()和__unset()
class MethodTest { private $data = array(); public function __set($name, $value){ $this->data[$name] = $value; } public function __get($name){ if(array_key_exists($name, $this->data)) return $this->data[$name]; return NULL; } public function __isset($name){ return isset($this->data[$name]) } public function unset($name){ unset($this->data[$name]); } } ?>
__sleep()和__wakeup()
当我们在执行serialize()和unserialize()时,会先调用这两个函数。例如我们在序列化一个对象时,这个对象有一个数据库链接,想要在反序列化中恢复链接状态,则可以通过重构这两个函数来实现链接的恢复。例子如下:
class Connection { protected $link; private $server, $username, $password, $db; public function __construct($server, $username, $password, $db) { $this->server = $server; $this->username = $username; $this->password = $password; $this->db = $db; $this->connect(); } private function connect() { $this->link = mysql_connect($this->server, $this->username, $this->password); mysql_select_db($this->db, $this->link); } public function __sleep() { return array('server', 'username', 'password', 'db'); } public function __wakeup() { $this->connect(); } } ?>
__toString()
// Declare a simple class class TestClass { public function __toString() { return 'this is a object'; } } $class = new TestClass(); echo $class; ?>
这个方法只能返回字符串,而且不可以在这个方法中抛出异常,否则会出现致命错误。
__invoke()
调用函数的方式调用一个对象时的回应方法。如下
class CallableClass { function __invoke() { echo 'this is a object'; } } $obj = new CallableClass; var_dump(is_callable($obj)); ?>
__set_state()
调用var_export()导出类时,此静态方法会被调用。
class A { public $var1; public $var2; public static function __set_state ($an_array) { $obj = new A; $obj->var1 = $an_array['var1']; $obj->var2 = $an_array['var2']; return $obj; } } $a = new A; $a->var1 = 5; $a->var2 = 'foo'; var_dump(var_export($a)); ?>
__clone()
当对象复制完成时调用。例如在设计模式详解及PHP实现:单例模式一文中提到的单例模式实现方式,利用这个函数来防止对象被克隆。
public class Singleton { private static $_instance = NULL; // 私有构造方法 private function __construct() {} public static function getInstance() { if (is_null(self::$_instance)) { self::$_instance = new Singleton(); } return self::$_instance; } // 防止克隆实例 public function __clone(){ die('Clone is not allowed.' . E_USER_ERROR); } } ?>
魔术常量(Magic constants)
PHP中的常量大部分都是不变的,但是有8个常量会随着他们所在代码位置的变化而变化,这8个常量被称为魔术常量。
-
__LINE__,文件中的当前行号
-
__FILE__,文件的完整路径和文件名
-
__DIR__,文件所在的目录
-
__FUNCTION__,函数名称
-
__CLASS__,类的名称
-
__TRAIT__,Trait的名字
-
__METHOD__,类的方法名
-
__NAMESPACE__,当前命名空间的名称
这些魔术常量常常被用于获得当前环境信息或者记录日志。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Alipay PHP...

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

The enumeration function in PHP8.1 enhances the clarity and type safety of the code by defining named constants. 1) Enumerations can be integers, strings or objects, improving code readability and type safety. 2) Enumeration is based on class and supports object-oriented features such as traversal and reflection. 3) Enumeration can be used for comparison and assignment to ensure type safety. 4) Enumeration supports adding methods to implement complex logic. 5) Strict type checking and error handling can avoid common errors. 6) Enumeration reduces magic value and improves maintainability, but pay attention to performance optimization.

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...
