[php classes and objects] magic methods
The content shared with you in this article is about [php classes and objects] magic methods, which has a certain reference value. Friends in need can refer to it
Magic methods(Magic methods)
__construct()__destruct()__callStatic()__set()__isset()__unset()__wakeup()__invoke()__clone() __debugInfo()
__sleep() and __wakeup()
public array __sleep ( void )void __wakeup ( void )
__sleep() is used to submit uncommitted data, or similar cleanup operations. For example, there are some very large objects, but they don't all need to be saved.
__wakeup() is used for deserialization operations. For example, re-establish the database connection or perform other initialization operations.
serialize() will check whether there is a magic method __sleep() in the class. If present, this method will be called first, and then the serialization operation will be performed. This function can be used to clean an object and return an array containing the names of all variables in the object that should be serialized. If the method returns nothing, NULL is serialized and an E_NOTICE level error is raised.
unserialize() checks whether there is a __wakeup() method. If it exists, the __wakeup method will be called first to prepare the resources needed by the object in advance.
Explanation of the above concepts
Serialize can convert variables, including objects, into continuous bytes data. You can save the serialized variables in a file or in Transmit over the network. Then deserialize it back to the original data. For a class you define before deserializing the object of the class, PHP can successfully store its object's properties and methods. Sometimes you may need an object to be deserialized before deserializing it. Executed immediately after serialization. For this purpose, PHP will automatically look for the __sleep and __wakeup methods.
When an object is serialized, PHP will call the __sleep method (if it exists). In After deserializing an object, PHP calls the __wakeup method. Neither method accepts parameters. The __sleep method must return an array containing the properties that need to be serialized. PHP discards the values of other properties. If there is no_ _sleep method, PHP will save all attributes.
Before the program is executed, the serialize() function will first check whether there is a magic method __sleep. If it exists, the __sleep() method will be called first and then executed. Serialization (serialization) operations. This function can be used to clean an object and return an array containing the names of all variables in the object. If the method returns nothing, NULL is serialized, resulting in an E_NOTICE error. In contrast, unserialize() checks whether there is a __wakeup method. If it exists, the __wakeup method will be called first to prepare the object data in advance.
__sleep method is often used to submit uncommitted data, or similar operations. At the same time, this function is very useful if you have some large objects that do not need to be saved. __wakeup is often used in deserialization operations, such as re-establishing a database connection, or performing other initialization operations.
__toString()
is used for how a class should respond when it is treated as a string. For example, echo $obj; should display something.
This method must return a string, otherwise a fatal error of E_RECOVERABLE_ERROR level will be issued. Exceptions cannot be thrown in the __toString() method. Doing so will result in a fatal error.
Example #2 简单示例<?php// Declare a simple classclass TestClass{ public function __toString() { return '类被当成字符串时tostring返回字符串'; // return intval('tostring返回值的内容不为字符串');//Recoverable fatal error: Method TestClass::__toString() must return a string value } }$class = new TestClass();echo $class;//echo (string)$class; // 未定义 __toString()方法,并将对象转换为字符串,报错Recoverable fatal error: Object of class TestClass could not be converted to string?>
It should be pointed out that
Before PHP 5.2.0, the __toString() method can only take effect when used directly with echo or print.
After PHP 5.2.0, it can be used in any string environment (such as through printf(), using the %s modifier), but cannot be used in non-string environments (such as using the %d modifier).
Since PHP 5.2.0, if an object that does not define the __toString() method is converted to a string, an E_RECOVERABLE_ERROR level error will be generated.
__invoke()
mixed __invoke ([ $... ] )
When trying to call an object by calling a function, the __invoke() method is automatically called. (PHP 5.3.0)
Example #3 使用 __invoke()<?phpclass CallableClass { function __invoke($x) { var_dump($x); //int(5) } }$obj = new CallableClass;$obj(5); var_dump(is_callable($obj)); //bool(true)?>
__set_state()
Related recommendations:
[php class and Object】Traversal
【php classes and objects】Anonymous class
【php classes and objects】Overload
The above is the detailed content of [php classes and objects] magic methods. For more information, please follow other related articles on the PHP Chinese website!

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











PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
