Php magic methods some learning Notes

Source: Internet
Author: User
Tags autoload
Magic methods start with _ in php5. they have magic functions that can bring many benefits to my development, next I will introduce some usage of magic methods and some magic methods in php. The magic method is to underline quot ;__ quo... magic methods start with _ in php5. they have magic functions that can bring many benefits to my development, next I will introduce some usage of magic methods and some magic methods in php.

The magic method starts with two underscores (_) and has special functions. it can be seen as the "syntactic sugar" of php ". Syntactic sugar refers to syntaxes that do not add new features to computer languages, but are more "sweet" to humans. Syntactic sugar often provides programmers with more practical programming methods or usage of some techniques, which is helpful for better coding style and easier to read code. However, it does not add anything new to the language. Php references and SPL are all syntactic sugar.

The instance code is as follows:

$tom = new family($student,'peking');  $tom = people->say();

The construct method in the above family class is a standard magic method. This magic method is also called constructor. If there is a constructor, there is a corresponding Xigou method, that is, the destruct method. Xigou method is executed when all references to an object are deleted, or when the object is explicitly destroyed. These two methods are common and the most swimming magic methods.

1. _ get, _ set

These two methods are designed for attributes that are not declared in the class and their parent class.

◆ _ Get ($ property) this method is triggered when an undefined property is called. the parameter passed is the name of the Accessed property.

◆ _ Set ($ property, $ value) when assigning values to an undefined property, this method is triggered and the passed parameter is the set property name and value.

Here, there is no declaration that the access control is "proteced" and "private" when an object is called (that is, an attribute with no access permission ).

2. _ isset and _ unset

◆ _ Isset ($ property) this method is called when the isset () function is called on an undefined property.

◆ _ Unset ($ property) this method is called when the unset () function is called on an undefined property.

Similar to the _ get method and _ set method, there is no declaration here, including the access control for the proteced and private attributes when the object is called (that is, the attribute with no access permission ).

3. _ call

_ Call ($ method, $ arg_array) when an undefined method is called, the undefined method here includes methods with no access permission; if the method does not exist, go to the parent class to find this method. if the parent class does not exist, call the _ call () method of this class. if the class does not contain _ call () find the _ call () method in the parent class.

4. _ autoload

_ Autoload function, which is automatically called when trying to use a class that has not been defined. By calling this function, the script engine has the last chance to load the required class before a PHP error fails.

To define a global automatic loading class, you must use the spl_autoload_register () method to register the processing class to the PHP Standard Library. the instance code is as follows:

Class Loader {static function autoload_class ($ class_name) {// find the correct $ class_name class and introduce it, if not, an exception is thrown.}/*** set the automatic loading of the object * spl_autoload_register-Register given function as _ autoload () implementation */spl_autoload_register (array ('loader ', 'autoload _ class'); $ a = new Test (); // Test is instantiated without using require for automatic loading. many frameworks use this method to automatically load classes.

Note: the exceptions thrown in the _ autoload function cannot be caught by the catch statement block and cause fatal errors. Therefore, the function itself should be captured.

5. _ construct and _ destruct

◆ _ Construct constructor: This method is called when an object is created. the advantage of using this method relative to PHP4 is that the constructor has a unique name, no matter what the name of its class is. in this way, you do not need to change the name of the constructor when changing the class name.

◆ _ Destruct destructor. PHP will call this method before the object is destroyed (that is, before it is cleared from memory. By default, PHP only releases the memory occupied by object properties and destroys object-related resources. The Destructor allows you to execute any code after using an object to clear the memory. When PHP decides that your script is no longer related to objects, the destructor will be called.

In the namespace of a function, this occurs when the function returns. For global variables, this occurs at the end of the script. If you want to explicitly destroy an object, you can assign any other value to the variable pointing to the object. Usually, the variable value is assigned NULL or unset is called.

6. _ clone

Object assignment in PHP 5 is a reference assignment. if you want to copy an object, you need to use the clone method. when you call this method, the object will automatically call the _ clone magic method, if you need to perform some initialization operations on object replication, you can implement them in the _ clone method.

7. _ toString

The _ toString method is automatically called when an object is converted into a string, for example, when an object is printed using echo.

If the class does not implement this method, the Object cannot be printed using echo; otherwise, the following error occurs: Catchable fatal error: Object of class test cocould not be converted to string in, this method must return a string. before PHP 5.2.0, the __tostring method takes effect only when echo () or print () is used in combination. PHP 5.2.0 and later can take effect in any string environment (for example, using the % s modifier through printf (), but cannot be used in non-string environment (for example, using the % d modifier ). From PHP 5.2.0, if an undefined _ toString method object is converted to a string, an E_RECOVERABLE_ERROR error is returned.

8. _ sleep and _ wakeup

◆ _ Used in sleep serialization

◆ _ Wakeup called when deserialization

Serialize () checks whether the class has a function named _ sleep. In this case, the function will run before any serialization. It can clear the object and should return an array containing all variable names to be serialized in the object.

The purpose of _ sleep is to close any database connection that an object may have, submit data in waiting or perform similar cleanup tasks. In addition, this function is useful if a very large object does not need to be fully stored.

Conversely, unserialize () checks the existence of a function with the magic name _ wakeup. If yes, this function can reconstruct any resources that an object may have. _ Wakeup is used to reconstruct any database connections that may be lost during serialization and process other re-initialization tasks.

9. _ set_state

When var_export () is called, this static method is called (effective from PHP 5.1.0 ). The unique parameter of this method is an array, which contains values by array ('properties' => value ,...) Class attributes in the format.

10. _ invoke (for PHP 5.3.0 and later versions)

When you try to call an object by calling a function, the __invoke method is automatically called.

11. _ callStatic (for PHP 5.3.0 and later versions)

It works in a way similar to the _ call () magic method, __callstatic () is used to handle static method calls. PHP does enhance the definition of the _ callStatic () method; it must be public and declared as static. Similarly, the __call () magic method must be defined as public, and all other magic methods must be.

Permanent address:

Reprint at will ~ Please bring the tutorial URL ^

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.