PHP Magic Methods/Functions
Citation
http://blog.csdn.net/inqihoo/article/details/9235103
In PHP syntax, some of the system's own method names, which begin with a double underscore, are invoked under certain circumstances. The so-called magic function.
They only work if you have already defined these magical methods for a given class. Also note that these methods cannot be called directly, but only through the events to intercept.
They play a crucial role in orientation-oriented programming. So personally think it is necessary to tidy up a bit. Here's a detailed collation of PHP's 15 magical functions:
1. __construct () and __destruct ()
This method is called when the __construct () object is initialized (this method is called after initialization is complete for the kernel). This method is used more. __destruct () This method is called when the object is destroyed. So when will the object be destroyed? One is the user actively destroys the object, and the second is automatically destroyed by the engine 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; } } Active destruction of objects $test = new test (); Unset ($test); Sleep (1); automatically destroy objects after completion of the program $test = new test (); Sleep (1);
2. __get () and __set ()
Two methods that are used very frequently in object-oriented programming. This method is called when you set and get properties of an object that do not allow access. It is important to note that it is not present or is not allowed to be read and written before it is called.
Therefore, for an object whose properties are not deterministic, it works well with these two methods.
__get ($name) Called when an object does not exist or cannot be accessed by a property. $name represents the name of the property to get
__set ($name, $value) is called when an object does not exist or an unreachable property is set. $name represents the name of the property to set, $value represents the value to set.
For example, we can construct a data record class with an indeterminate attribute, the classes record { protected $_data; Public Function __get ($name) { 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 calling the method Isset () to determine whether an object exists for a property, call Unset () to unregister a property. And when these properties are not present or inaccessible, the __isset () and __unset () methods are called separately
Slightly the same as the previous __get () and __set (). is called when a property does not exist or is inaccessible
__isset ($name) Called when the Method Isset () method is called to determine the class property that is not accessible. $name represents the property name.
__unset ($name) Called when the Method Unset () method is called to delete an Inaccessible class property. $name represents the property name.
For 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 property '. $name. ' Exists '. Php_eol; } Public Function __unset ($name) { echo ' the property '. $name. ' Can is not unset '. Php_eol; } } $people = new People (' Andrew ', ' Male ', '); Isset ($people->name); Isset ($people->real_name); unset ($people->_age);
4. __call () and __callstatic ()
Earlier, we found that the __get () method is called when the property of the object is obtained, if this property does not exist. So what if this method does not exist if the method of this object is called? The PHP engine automatically calls the __call () method.
Similarly, if a static method is called and does not exist, the __callstatic () method is called. It is important to note that __callstatic () is used as a static method and is supported only in versions above php5.3.
__call ($method, $args) Call object method does not exist or is not allowed to be invoked when this method is called. $method represents the method name of the call, $args the parameter that represents the call
__callstatic ($method, $args) This method is called when the static method of the calling object does not exist or is not allowed to be called. $method represents the method name of the call, $args the parameter that represents the call.
[PHP] View plaincopy
For example: we assume that only two behaviors are skipped , class people {Public function jumps () { 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 the public static function __callstatic ($method, $args) { echo ' We can not ' is available under the php5.3 version. $ Method. Php_eol; } } $people = new People (); $people->jump (); $people->walk (); $people->fly (); People::fly ();
5. __sleep () and __wakeup ()
These two methods, I see, is sleep and wake up. What does that have to do with the object? Sometimes I can't remember when I use it. In fact, we simply remember that in PHP there is a way to let the object sleep, called Searialize (),
It serializes the properties of an object to facilitate preservation. The Unsearialize () method is to unpack the saved serialized data into an object. Also called Wake. In response, when sleeping, PHP calls the __sleep () method, which
The return value must be an array representing the property items that need to be saved, and data for resource types such as file handles and database connections cannot be serialized. Similarly, when waking an object, PHP calls the __wakeup () method,
But unlike __sleep (), it returns a null value. The saved properties will be undone. What's the use of it? As we said, Searialize is not able to save resources. So what if we want to use these resources when we wake up?
Do? The answer is yes, re-created? Where do you create the right one? Of course it is inside the __wakeup () method, because this method is called every time it wakes up. Now we know the use of these two methods.
__sleep () is called when the Searialize () method is called, and the return value is an array representing the data item that needs to be serialized.
__wakeup () is called when the Unsearizlie () method is called. Typically used to initialize a resource object upon wakeup.
[PHP] View plaincopy
For example, we have a user class, and the user name and gender are all 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 you cast an object to a string type, the Echo object is used in a function of a string parameter. Note: The return value of this method must be a string.
[PHP] View plaincopy
For 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 the object is copied. We know that in PHP. $a as an object, $b = when $a. The $b is a $ A reference. When a $ A change occurs. $b will change as well. So in order to make $b not change, we need to use $b=clone $a;
Then, when $ A is called clone, the engine automatically calls the __clone () method
[PHP] View plaincopy
For example: The following is a simple example of 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; To the object-oriented comparison of the students, must be a singleton mode is not unfamiliar. When PHP does a singleton mode, remember to disable the Clone method. Because in singleton mode, objects are not allowed to be copied. The following example class Onlyone {//Singleton object private static $_instance; Do not allow external and subclass calls to initialize method private function __construct () {}//Do not allow copy of public function __clone () { throw new Exception (' Not allow to clone me '); }//Get Singleton object public static function getinstance () {if (self::$_instance! = null) {R Eturn 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 primarily used to automatically load classes. How does it load automatically? We all know that in PHP, to use a class in another file, you need to use the require or include method
(including require_once and Include_one) are imported in. Then if the class I want to use is not imported, the engine will call the __autoload () method automatically. With this feature, when our class name and class file are regularly
, we can use the __autoload () method to allow the program to import files automatically, depending on the class name that needs to be imported. This function plays an important role in many MVC frameworks.
__autoload ($name) $name indicates the class name that needs to be imported automatically
[PHP] View plaincopy
We make the rule class name with the directory name plus download line stitching. For example, the class Model_config_xml represents the model/config/normal.php file. How do we implement an auto-load //class file model/config/normal.php contains classes such as: 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"); } There will be no more require (' model/config/normal.php ') $config = new Model_config_normal ();
9. __set_state ()
This method is not used much. Before you know this method, you need to know the Var_export () function, similar to Var_export () and Var_dump (), to output a string representation of a variable. The difference between him and Var_dump is that it's legal to return the results.
PHP code. This code can be performed by Eval. Note: This method is a static method and is supported in versions above php5.1.
[PHP] View plaincopy
For 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 =; $code =var_export ($test, true); Echo $code. Php_eol; Eval (' $new = '. $code. '; '); Var_dump ($new);
__invoke ()
When I first came into contact with this method, I could not see what it was doing at one glance. The main thing is not to understand what invoke means. Then I looked up the dictionary to understand. It means call. English is too bad to hurt.
In PHP, this method is used to use the object as a method. This method is called. Very simple. Note that this method is supported only for 5.3 or more versions.
[PHP] View plaincopy
Class Invoke {public function __invoke () { echo ' I can run '. Php_eol; } } $invoke = new Invoke (); $invoke ();