Overview
In object-oriented programming, PHP offers 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 need to be displayed but is based on a specific condition. This article briefly summarizes the magic methods provided in PHP.
Before you start
Before summarizing the Magic method for PHP, define two classes so that the following example uses:
Copy Code code as follows:
<?php
Class 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 > 100) {
$charge = 100;
}
$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 is "destroyed" means that there is no reference to the object, such as a variable that refers to the object being deleted (unset), a redistribution, or the end of the script execution, which calls the destructor.
__construct ()
The __construct () constructor is the most commonly 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 exceptions that occur in the constructor will prevent the object from being created.
Copy Code code 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.
Copy Code code as follows:
Declaring a constructor as a private method prevents objects from being created outside the class, which is often used in simple mode.
__desctruct ()
Destructors are usually called when an object is destroyed, and the destructor does not receive any arguments. Often performs some cleanup work in destructors, such as shutting down a database connection.
Attribute overload (Property overloading)
One thing to note is that "overload" in PHP is not quite the same as the overloads of most other languages, although it all implements the same functionality.
The two magic methods involved in attribute overloading are primarily used to handle property access, defining what happens when we try to access an attribute that is not present (or inaccessible).
__get ()
The Magic Method __get () is invoked when we try to access a nonexistent property. It receives 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 that works here, as shown in the following code:
Copy Code code as follows:
Class Device {
Public Function __get ($name) {
if (Array_key_exists ($name, $this->data)) {
return $this->data[$name];
}
return null;
}
}
The most common place for this magic method is to extend access control by creating a "read-only" attribute. In the battery class above, there is a private property $charge, which we can extend by __get () Magic method to be readable outside the class but cannot be modified. The code is as follows:
Copy Code code 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 invoked when we try to modify an inaccessible property, it receives two parameters, a name representing the property, and a value representing the property. The sample code is as follows:
Copy Code code as follows:
Class Device {
Public Function __set ($name, $value) {
Use the property name as the array key
$this->data[$name] = $value;
}
}
__isset ()
The __isset () Magic method is invoked when a isset () method is invoked on an inaccessible property, which 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:
Copy Code code as follows:
Class Device {
Public Function __isset ($name) {
Return array_key_exists ($name, $this->data);
}
}
__unset ()
The __unset () Magic method is invoked when the call to the unset () function destroys an inaccessible property, and it receives a parameter that expresses the name of the property.
Object into a string
Sometimes we need to show the object as 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 invoked when we use an object as a string, and it does not receive any arguments. This method allows us to define the representation of an object. The code is as follows:
Copy Code code 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 (), which is invoked when we use the Var_export () function to output an object. The Var_export () function converts a PHP variable to PHP code that receives an associative array containing the property values of an object as an argument. The sample code is as follows:
Copy Code code 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 values 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 actually replicate an object, we need to use the Clone keyword.
This "pass by reference" policy also applies to objects that are 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 internal object. The sample code is as follows:
Copy Code code as follows:
$device = new Device (new Battery (), ' imagic ');
$device 2 = Clone $device;
$device->battery->setcharge (65);
Echo $device 2->battery->charge;
65
__clone ()
__clone () Magic Method __clone () can solve the above problem. The Magic method is invoked when the Clone keyword is used on an object. In this magic method, we can implement the cloning of any child objects, the code is as follows:
Copy Code code as follows:
Class Device {
...
Public Function __clone () {
Copy our Battery object
$this->battery = Clone $this->battery;
}
...
}
Object serialization
Serialization is the process of converting arbitrary data into string format. Serialization is often used to save an entire object to a database or write to a file. When the stored data is deserialized, we can get the object before the serialization. However, not all data can be serialized, such as database connections. Luckily, there is a magic trick that can help us solve this problem.
__sleep ()
The Magic Method __sleep () is invoked when serializing an object (the call to serialize ()). It does not receive any parameters and should return an array that contains all the attributes that should be serialized. In this magic method, you can also perform some other action.
One thing to be aware of is that you do not do any destructor in the function, because this can affect the running object.
The sample code is as follows:
Copy Code code 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 invoked when deserializing a stored object. It does not receive any parameters, nor does it have any return values. You can use it to handle database connections or resources that are lost during serialization. The code is as follows:
Copy Code code as follows:
Class Device {
//...
Public Function __wakeup () {
Reconnect to the network
$this->connect ();
}
//...
}
Method overload
PHP also has two magic methods associated with member methods __call () and __callstatic (), which are similar to property overload methods.
__call ()
The Magic Method __call () is invoked when a method that does not exist or is inaccessible is invoked. It receives two parameters, one is the name of the method being invoked, and the other is an array containing the function arguments. We can use this method to invoke a function of the same name in a child object.
In this example, note the function Call_user_func_array (), which allows us to dynamically invoke a named function.
The sample code is as follows:
Copy Code code as follows:
Class Device {
//...
Public Function __call ($name, $arguments) {
Make sure we child object has
if (method_exists ($this->connection, $name)) {
Forward the call to my child object
return Call_user_func_array (Array ($this->connection, $name), $arguments);
}
return null;
}
//...
}
__callstatic ()
The Magic Method __callstatic () is the same as the function of __call (), except that the method is invoked when it attempts to access a static method that is not present or inaccessible. The sample code is as follows:
Copy Code code as follows:
Class Device {
//...
public static function __callstatic ($name, $arguments) {
Make sure we class has this method
if (method_exists (' Connection ', $name)) {
Forward the static call to our class
return Call_user_func_array (Array (' Connection ', $name), $arguments);
}
return null;
}
//...
}
To use an object as a function
Sometimes we need to use objects as functions. Use an object as a function, just as we would use other normal functions to pass the argument.
__invoke () (PHP 5.3)
The Magic Method __invoke () is invoked when an attempt is used to use an object as a function. Any parameters defined in the method will be used as arguments to the function. The sample code is as follows:
Copy Code code 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
Other: __autoload ()
__autoload () method is not a magic method, but this method is very useful. However, for updates to the PHP version, the function is not recommended and replaced by the Spl_auto_register () function.