Magic Methods in PHP some learning notes

Source: Internet
Author: User
Tags constructor modifier php error serialization valid

Magic method is a two underline "__" The beginning, has a special role of some methods, can be seen as PHP's "grammatical sugar."

Grammatical sugars are grammars that do not add new functionality to computer languages but are more "sweet" to humans. Grammatical sugars tend to provide programmers with more practical programming methods or techniques that are useful for better coding styles and easier for code to read. But it doesn't add anything new to the language. PHP quotes, SPL, etc. belong to the grammatical candy.

The code is as follows Copy Code

$tom = new Family ($student, ' Peking ');
$tom = People->say ();

The construct method in the family class above is a standard magic method. This magic method is also called the construction method. There are structured methods that have a corresponding method of the destruct, that is, the method of using the method, where all references to an object are deleted or executed when the object is explicitly destroyed. These two methods are common and the most swimming magic methods.

1, __get, __set

The two methods are designed for properties that are not declared in the class and their parent classes.

__get ($property) When an undefined property is invoked, this method is triggered and the parameter passed is the name of the property being accessed.

When __set ($property, $value) assigns a value to an undefined property, this method is triggered and the passed parameter is the property name and value that is set.

The absence of a declaration here includes a property (that is, a property that has no access) when an object invocation is used, and the access control is proteced,private.

2, __isset, __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.

As with the __get method and the __set method, there is no declaration that includes properties that have access control as proteced,private when using object invocation (that is, properties that do not have permission to access).

3, __call

__call ($method, $arg _array) This method is called when an undefined method is invoked.

Undefined methods here include methods that do not have access to permissions; If the method does not exist, find this method in the parent class, and if the parent class does not exist, call the __call () method of this class, and if there is no __call () method in this class, find the __call () method in the parent class.

4, __autoload

The __autoload function, which is invoked automatically when an attempt is made to use a class that has not been defined. By calling this function, the script engine had the last chance to load the class that was required before the PHP error failed.

If you want to define a global automatic load class, you must register the processing class with the Spl_autoload_register () method in the PHP standard library:

  code is as follows copy code

<?php
Class loader  
 {         
     static function Autoload_class ($class _name)         {          
   /Find the correct $class_name class and introduce, no then throw an exception           
    }         
 }     
/**
*  automatic loading of settings objects         
*  spl_autoload_register-register given function as __autoload () implementation   & nbsp;  
*/  
Spl_autoload_register (Array (' Loader ', ' Autoload_class '));  
  $a = new Test ();//test require instantiated for automatic loading, many frameworks automatically load classes in this way

Note: The exception thrown in the __autoload function cannot be caught by a catch statement block and can cause a fatal error, so it should be caught in the function itself.

5, __construct, __destruct

__construct construction method, when an object is created to call this method, the advantage of using this method relative to PHP4 is that you can make the constructor have a unique name, regardless of the name of the class in which it resides. So that when you change the name of a class, you do not need to change the name of the constructor method.

__destruct destructor, PHP calls this method before the object is destroyed (that is, before it is purged from memory). By default, PHP releases only the memory occupied by the object's properties and destroys the object-related resources, and the destructor allows you to execute arbitrary code to erase memory after using an object. Destructors are invoked when PHP determines that your script is no longer related to objects.

Within the namespace of a function, this occurs when the function return. 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 that points to the object. The variable is usually assigned on duty as null or the unset is invoked.

6, __clone

The object assignment in PHP 5 is the reference assignment used, and if you want to copy an object, you need to use the Clone method, and calling this method is an object that automatically invokes the __clone magic method, which can be implemented in the __clone method if some initialization action is required on the object copy.

7, __tostring

The __tostring method is invoked automatically when an object is converted to a string, such as when the object is printed with Echo.

If the class does not implement this method, the object cannot be printed through ECHO, or it will display: Catchable fatal Error:object of class test could not is converted to string, this method must return a character String.

Before PHP 5.2.0, the __tostring method takes effect only if echo () or print () is used in conjunction. After PHP 5.2.0, it can take effect in any string environment (for example, by printf (), using the%s modifier) but not in a non-string environment (such as using the%d modifier). From PHP 5.2.0, if you convert an object that does not define a __tostring method to a string, a e_recoverable_error error is reported.

8, __sleep, __wakeup

When __sleep is serialized, use

__wakeup Drag when the row is called

Serialize () checks whether the class has a magic name __sleep function. If so, the function will run before any serialization. It can clear the object and should return an array that contains all the variable names that should be serialized in the object.

The purpose of using __sleep is to turn off any database connections that the object might have, commit the waiting data, or perform similar cleanup tasks. Also, this function is useful if you have a very large object and you do not need to store it completely.

Conversely, unserialize () checks the existence of a function that has a magic name __wakeup. If present, this function can reconstruct any resources that the object might have. The purpose of using __wakeup is to reconstruct any database connections that may be lost in serialization and to handle other reinitialization tasks.

9, __set_state

When Var_export () is invoked, this static method is invoked (valid from PHP 5.1.0).

The unique argument for this method is an array that contains a press array (' property ' => value, ...) The class attribute of the format arrangement.

10, __invoke (PHP 5.3.0 version is valid)

The __invoke method is invoked automatically when an attempt is made to call an object in the form of a call to a function.

11, __callstatic (PHP 5.3.0 version is valid)

It works like the __call () Magic Method, __callstatic () to handle static method calls.

PHP does strengthen the definition of the __callstatic () method, it must be public and must be declared static. Similarly, the __call () Magic method must be defined as public, and all other magic methods must be so

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.