Overview
In object-oriented programming, PHP provides a series of magic methods that provide a lot of convenience for programming. The Magic method in PHP usually starts with (two underscores) and does not require a display of calls but a certain set of conditions. This article briefly summarizes the magic methods available in PHP.
Before you begin
Before summarizing the Magic method of PHP, define two classes so that the following example uses:
The code is as follows:
<?phpclass Device {public $name; public $battery; Public $data = Array (); public $connection; protected function Connect () { $this->connection = ' resource '; Echo $this->name. ' Connected '. Php_eol; } protected function Disconnect () { $this->connection = null; Echo $this->name. ' Disconnected '. Php_eol;} } Class Battery { private $charge = 0; Public Function Setcharge ($charge) { $charge = (int) $charge; if ($charge < 0) { $charge = 0; } ElseIf ($charge >) { $charge =; } $this->charge = $charge; }}? >
The device class has four member properties and two member methods. The battery class has a member property and a member method.
Constructors and destructors
Constructors and destructors are called when objects are created and destroyed, respectively. An object being "destroyed" means that there is no reference to the object, such as a variable that references the object is deleted (unset), re-assigned, or the end of the script execution, and the destructor is called.
Construct ()
The construct () constructor is the most frequently used function so far. When you create an object, you can do some initialization work in the constructor. You can define any number of parameters for the constructor, as long as you pass in the corresponding number of arguments when instantiating. Any exception that occurs in the constructor prevents the creation of the object.
The code is as follows:
Class Device {public function construct (Battery $battery, $name) { $this->battery = $battery; $this->name = $name; $this->connect (); }}
In the example code above, the constructor for the device class assigns a value to the member property and calls the Connect () method.
Declaring constructors as private methods prevents objects from being created outside the class, which is often used in simple interest mode.
Desctruct ()
Destructors are usually called when an object is destroyed, and destructors do not receive any parameters. Some cleanup work is often performed in destructors, such as shutting down database connections, and so on.
Attribute overloading (Property overloading)
One thing to note is that "overloading" in PHP is not the same as the overloads of most other languages, although they all implement the same functionality.
The two magic methods involved in property overloading are primarily used to handle property access, and define what happens when we try to access a property that does not exist (or is inaccessible).
Get ()
The Magic Method get () is called when we try to access a nonexistent property. It takes a parameter that represents the name of the Access property and returns the value of the property. In the device class above, there is a data property, which is here to work, such as the following code:
The code is as follows:
Class Device {public function get ($name) { if (array_key_exists ($name, $this->data)) { return $ this->data[$name]; } return null;} }
The most common use of this magic method is to extend access control by creating a "read-only" property. In the battery class above, there is a private property $charge, which we can extend by the Get () Magic method to be readable but not modifiable outside of the class. The code is as follows:
The code is as follows:
Class Battery { private $charge = 0; Public function Get ($name) { if (isset ($this-$name)) { return $this-$name; } return null;} }
Set ()
The set () Magic method is called when we try to modify an inaccessible property, which receives two parameters, a name that represents the property, and a value that represents the property. The sample code is as follows:
The code is as follows:
Class Device {public function set ($name, $value) {//Use the property name as the array key $this->da ta[$name] = $value; }}
Isset ()
The Isset () Magic method is called when the Isset () method is called on an inaccessible property, and it receives a parameter that represents the name of the property. It should return a Boolean value to indicate whether the property exists. The code is as follows:
The code is as follows:
Class Device {public function isset ($name) { return array_key_exists ($name, $this->data);} }
Unset ()
The unset () Magic method is called when the unset () function is called to destroy an inaccessible property, and it receives a parameter that describes the name of the property.
Convert object to String
Sometimes we need to show the object in the form of a string. If we print an object directly, the program will output an error message: PHP catchable fatal Error:object of class Device could not being converted to string
ToString ()
ToString () is called when we use the object as a string, and it does not receive any parameters. This method allows us to define the representation of an object. The code is as follows:
The code is as follows:
Class Device {public function toString () { $connected = (isset ($this->connection))? ' Connected ': ' Disconnected '; $count = count ($this->data); Return $this->name. ' Is '. $connected. ' With '. $count. ' Items in memory '. Php_eol; } ...}
Set_state () (PHP 5.1)
The static Magic Method, Set_state (), calls the method when we use the Var_export () function to output an object. The Var_export () function is used to convert a PHP variable to PHP code, which receives an associative array containing the object's property values as a parameter. The sample code is as follows:
The code is as follows:
Class Battery { //... public static function set_state (array $array) { $obj = new self (); $obj->setcharge ($array [' Charge ']); return $obj; } //...}
Cloning objects
By default, objects are passed by reference. Therefore, when an object is assigned to another variable, only one reference to the object is created, and the object is not copied. In order to achieve a real copy of an object, we need to use the Clone keyword.
This "pass-by-reference" policy also applies to objects contained within an object. Even if we clone an object, any object inside the object will not be cloned, so the end result is that two objects share the same inner object. The sample code is as follows:
$device = new Device (new Battery (), ' imagic '); $device 2 = Clone $device; $device->battery->setcharge (+), Echo $device 2->battery->charge;//65
Clone ()
Clone () Magic Method Clone () can solve the above problem. The Magic method is called when the Clone keyword is used on an object. In this magic method, we can implement any child object cloning, the code is as follows:
The code is as follows:
Class Device { ... Public Function Clone () { //Copy our Battery object $this->battery = Clone $this->battery; } . ..}
Serialization of objects
Serialization is the process of converting any data into a string format. Serialization is typically used to store an entire object in a database or write to a file. When deserializing the stored data, we can get the object before the serialization. However, not all data can be serialized, such as database connections. Fortunately, there is a magic method that can help us solve this problem.
Sleep ()
The Magic Method Sleep () is called when serializing an object (called Serialize ()). It does not receive any parameters, and it should return an array containing all the attributes that should be serialized. In this magic method, you can also perform some other operations.
One thing to note is that you should not do any of the destructors in this function, as this may affect the objects that are running.
The sample code is as follows:
Class Device {public $name; public $battery; Public $data = Array (); public $connection; //... Public Function Sleep () { return array (' name ', ' battery ', ' data '); } //...}
Wakeup ()
The Magic Method Wakeup () is called when the stored object is deserialized. It does not receive any parameters, nor does it have any return values. It can be used to handle database connections or resources that are lost during serialization. The code is as follows:
The code is as follows:
Class Device { //... Public Function Wakeup () { //reconnect to the network $this->connect (); } //...}
Method overloading
PHP also has two magic methods associated with member methods call () and callstatic (), which are similar to property overloading methods.
Call ()
The Magic Method call () is called when a method that does not exist or is not accessible is called. It receives two parameters, one is the name of the method being called, and the other is an array containing the function arguments. We can use this method to invoke a function with the same name in the child object.
In this example, note that the function Call_user_func_array (), which allows us to invoke a named function dynamically.
The sample code is as follows:
Class Device { //... Public Function call ($name, $arguments) { //Do sure our child object have this method if (Method_exists ($thi S->connection, $name)) {//forward the call to our child object return Call_user_func_array (Array ($this, Connection, $name), $arguments); } return null; } //...}
Callstatic ()
Magic Method Callstatic () is the same as the function of call (), except that the method is called when it attempts to access a static method that does not exist or is inaccessible. The sample code is as follows:
Class Device { //... public static function callstatic ($name, $arguments) { //Make sure our class have this method if (method_exist S (' Connection ', $name)) { //forward the static call to our class return Call_user_func_array (' Connection ' , $name), $arguments); } return null; } //...}
To use an object as a function
Sometimes we'll need to use the object as a function. Use the object as a function, as we can with other normal functions, to pass the argument.
Invoke () (PHP 5.3)
The Magic Method Invoke () is called when trying to use an object as a function. Any parameters that are defined in the method are treated as arguments to the function. The sample code is as follows:
Class Device { //... Public function Invoke ($data) { echo $data; } //...} $device = new Device (new Battery (), ' imagic '), $device (' Test '),//EQUIV to $device->invoke (' Test ')//Outputs:test
Others: AutoLoad ()
The
AutoLoad () method is not a magic method, but this method is useful. However, for updates to the PHP version, the function is not recommended and is replaced by the Spl_auto_register () function.