PHP magic step/function explanation

Source: Internet
Author: User
PHP magic methods/function details are introduced from: functions. The so-called magic function. Only when PHP magic methods/functions are described
Reference:
Http://blog.csdn.net/inqihoo/article/details/9235103

In php syntax, some built-in method names begin with double underscores and are called under certain circumstances. The so-called magic function.
They work only when you have defined these magic methods for a given class. Note that these methods cannot be called directly, but can only be called through events to be intercepted.
They play a crucial role in object-oriented programming. So I personally think it is necessary to sort it out. The following describes the 15 Magic functions in php:

1. _ construct () and _ destruct ()
The _ construct () object calls this method during initialization (for the kernel, this method is called after initialization). This method is used a lot. _ Destruct () this method is called when an object is destroyed. When will the object be destroyed? First, the user actively destroys the object, and second, the engine automatically destroys the object when the program ends.
[Php] view plaincopy
Class People {protected $ _ alive; public function _ construct () {$ this-> _ alive = true; echo 'birth '. PHP_EOL;} public function _ destruct () {$ this-> _ alive = false; echo 'die '. PHP_EOL ;}}// actively destroys the object $ test = new Test (); unset ($ test); sleep (1 ); // automatically destroy the object $ test = new Test (); sleep (1 );


2. _ get () and _ set ()
In object-oriented programming, two methods are frequently used. this method is called when the access to object attributes is not allowed. It must be noted that it is called only when it does not exist or cannot be read or written.
Therefore, when the attributes of an object are uncertain, these two methods work well.

_ Get ($ name) is called to obtain an attribute that does not exist or that cannot be accessed. $ name indicates the name of the attribute to be obtained.
_ Set ($ name, $ value) is called when an attribute that does not exist or is inaccessible to an object is set. $ name indicates the name of the attribute to be set, and $ value indicates the value to be set.

// For example, we can construct a data Record class Record {protected $ _ data; public function _ get ($ name) with uncertain attributes) {if (isset ($ this-> _ data [$ name]) {return $ this-> _ data;} return false;} public function _ set ($ name, $ value) {$ this-> _ data = $ value ;}$ record = new Record (); $ record-> name = 'Andrew '; echo 'My name is '. $ record-> name. PHP_EOL;


3. _ isset () and _ unset ()
These two methods are used less. When the call method isset () is used to determine whether an object has a certain attribute and unset () is called to deregister an attribute. When these attributes do not exist or are inaccessible, the _ isset () and _ unset () methods are called respectively.
It is slightly the same as the previous _ get () and _ set. Is called when a property does not exist or is not accessible.

_ Isset ($ name) is called when the isset () method is called to determine inaccessible class attributes. $ name indicates the attribute name.
_ Unset ($ name) is called when the call method unset () method deletes inaccessible class attributes. $ name indicates the attribute name.
// Example: class People {public $ name; public $ sex; private $ _ age; public function _ construct ($ name, $ sex, $ age) {$ this-> name = $ name; $ this-> sex = $ sex; $ this-> _ age = $ age;} public function _ isset ($ name) {echo 'The properties '. $ name. 'Not exists '. PHP_EOL;} public function _ unset ($ name) {echo 'The properties '. $ name. 'Can not be unset '. PHP_EOL; }}$ people = new People ('Andrew ', 'male', 28); isset ($ people-> name); isset ($ people-> real_name ); unset ($ people-> _ age );


4. _ call () and _ callStatic ()
Previously, we found that the _ get () method is called if this property does not exist when obtaining the object property. What if this method does not exist when calling the method of this object? The php engine automatically calls the _ call () method.
Similarly, if a static method is called and does not exist, the _ callStatic () method is called. Note that __callstatic () is a static method and is only supported in php5.3 or later versions.

_ Call ($ method, $ args) is called when the object method does not exist or cannot be called. $ Method indicates the name of the called method, and $ args indicates the called parameter.
_ CallStatic ($ method, $ args) this method is called when the static method of the called object does not exist or cannot be called. $ Method indicates the name of the called method, and $ args indicates the called parameter.
[Php] view plaincopy
// For example, we assume that only one member can skip two actions: class People {public function jump () {echo 'I can jump '. PHP_EOL;} public function walk () {echo 'I can walk '. PHP_EOL;} public function _ call ($ method, $ args) {echo 'I can not '. $ method. PHP_EOL;} // this method must be a static method, and public static function _ callStatic ($ method, $ args) {echo 'We can not 'can be used in php5.3 '. $ method. PHP_EOL; }}$ people = new People (); $ people-> jump (); $ people-> walk (); $ people-> fly (); People :: fly ();


5. _ sleep () and _ wakeup ()
The two methods are sleeping and waking. What is the relationship with the object? Sometimes it cannot be used. In fact, we can simply remember that there is a method in php for sleeping objects, called searialize (),
It serializes the attributes of an object for easy storage. The unsearialize () method is to unbind the stored serialized data into an object. Also called wakeup. Correspondingly, when sleeping, php will call the _ sleep () method.
The returned value must be an array, indicating the attribute items to be saved. data of file handles, database connections, and other resource types cannot be serialized and saved. Similarly, when an object is awakened, php calls the _ wakeup () method,
But unlike _ sleep (), the return value is null. All saved attributes are unlocked. So what is its use? As we just said, searialize cannot save resources. What if we want to use these resources when we wake up?
? Are you sure you want to recreate it? Where can I create a suitable one? Of course it is in the _ wakeup () method, because this method will be called every time you wake up. Now we know the purpose of these two methods.

_ Sleep (): When the searialize () method is called, the returned value is an array, indicating the data items to be serialized.
_ Wakeup () is called when the unsearizlie () method is called. It is generally used to initialize a resource object during wake-up.
[Php] view plaincopy
// For example, we have a user class. the user name and gender are class attributes. The User's password exists in the file Class User {public $ username; public $ sex; public $ passFile; private $ _ password; public function _ construct ($ username, $ sex, $ passFile) {$ this-> username = $ username; $ this-> sex = $ sex; $ this-> passFile = $ passFile; $ this-> _ password = file_get_contents ($ passFile);} public function getPassword () {return $ this-> _ password;} public function _ sleep () {return array ('username', 'sex', 'passfile',);} public function _ wakeup () {$ this-> _ password = file_get_contents ($ this-> passFile) ;}}$ user = new User ('Andrew ', 'male', 'Pass. data '); $ serializeData = serialize ($ user); echo $ serializeData. PHP_EOL; $ user = unserialize ($ serializeData); echo $ user-> getPassword (). PHP_EOL;


6. _ toString ()
This method is called when the object needs to be converted to a string. For example, when the echo object is forcibly converted to the string type, it is used in the string parameter function. note: The return value of this method must be a string.
[Php] view plaincopy
// Example: class Info {public function _ toString () {return "info" ;}}$ info = new Info (); echo $ info. PHP_EOL; echo md5 ($ info ). PHP_EOL; echo (String) $ info. PHP_EOL; echo substr ($ info, 0, 2 ). PHP_EOL;


7. _ clone ()
This method is called when copying an object. We know that. $ a is an object in php, $ B = $. $ B is a reference of $. When $ a changes. $ B also changes. To keep $ B unchanged, we need to use $ B = clone $;
When $ a calls clone, the engine automatically calls the _ clone () method.
[Php] view plaincopy
// Example: the following simple example class Data {public $ value; public function _ clone () {echo "Clone myself ". PHP_EOL ;}}$ data = new Data (); $ data-> value = 4; $ newData = clone $ data; $ data-> value = 5; echo "The data value is :". $ data-> value. PHP_EOL; echo "The new data value is :". $ newData-> value. PHP_EOL; // for those who are familiar with object orientation, the singleton mode is certainly no stranger. Remember to disable the clone method when using the PHP Singleton mode. In Singleton mode, copying objects is not allowed. The following example shows the class OnlyOne {// Singleton object private static $ _ instance; // The initialization method private function _ construct () is not allowed for external and subclass calls () {} // public function _ clone () {throw new Exception ('not allow to clone me') cannot be copied ');} // Obtain the public static function getInstance () {if (self ::$ _ instance! = Null) {return self ::$ _ instance;} self ::$ _ instance = new self (); return self ::$ _ instance ;}}$ onlyOne = OnlyOne:: getInstance (); $ newOne = clone $ onlyOne;


8. _ autoload ()
Autoload is automatically loaded as the name implies. It is mainly used to automatically load classes. So how to automatically load it? We all know that in php, The require or include method is required to use classes in another file.
(Including require_once and include_one. If the class I want to use is not imported, the engine will automatically call the _ autoload () method. With this feature, when our class names and class files are regular
During local storage, we can use the _ autoload () method to let the program automatically import files based on the class name to be imported. This function plays an important role in many MVC frameworks.
_ Autoload ($ name) $ name indicates the name of the class to be automatically imported
[Php] view plaincopy
// The name of the rule class is spliced with the directory name and download line. For example, Model_Config_Xml indicates Model/Config/Normal. php file. how can we automatically load the // class file Model/Config/Normal. php contains the following classes: class Model_Config_Normal {public function _ construct () {echo "Init Model_Config_Normal ". PHP_EOL ;}} function _ autoload ($ name) {$ classPath = str_replace ('_', DIRECTORY_SEPARATOR, $ name); require_once ("$ classPath. php ");} // no more require ('Model/Config/Normal. php ') $ config = new Model_Config_Normal ();


9. _ set_state ()
This method is rarely used. Before learning about this method, you must first know the var_export () function. var_export () is similar to var_dump (), and output a variable string representation. The difference between var_dump and var_dump is that it returns valid results.
Php code. this code can be executed by eval. note: This method is a static method and is only supported in php5.1 and later versions.
[Php] view plaincopy
// Example: class Test {public $ name; public $ age; public static function _ set_state ($ data) {$ obj = new Test (); $ obj-> name = $ data ['name']; $ obj-> age = $ data ['age'] + 1; return $ obj ;}} $ test = new Test (); $ test-> name = 'Andrew '; $ test-> age = 27; $ code = var_export ($ test, true ); echo $ code. PHP_EOL; eval ('$ new = '. $ code. ';'); var_dump ($ new );


10. _ invoke ()
When I first came into contact with this method, I couldn't see what it was doing. I don't understand what invoke means. Later, I checked the dictionary to understand it. Call. Poor English.
In php, this method is used to use objects as methods. This method will be called. Very simple. Note that this method is only supported by version 5.3 and later.
[Php] view plaincopy
class Invoke {        public function __invoke()      {          echo 'I can run'.PHP_EOL;      }  }    $invoke = new Invoke();  $invoke();  

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.