This article describes the functions and usage of common magic methods in PHP. This article describes constructor and destructor _ construct () and _ desctruct () and PropertyOverloading _ get () and _ set (), _ isset () and other magic methods. For more information, see
Overview
In object-oriented programming, PHP provides a series of magic methods, which provide a lot of convenience for programming. The magic method in PHP usually starts with _ (two underscores) and starts with a specific condition instead of a display call. This article briefly summarizes the magic methods provided in PHP.
Before getting started
Before summarizing the magic methods of PHP, define two classes for the following example:
The Code is 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;
}
Else'if ($ charge> 100 ){
$ Charge = 100;
}
$ This-> charge = $ charge;
}
}
?>
The Device class has four member attributes and two member methods. The Battery class has a member attribute and a member method.
Constructor and destructor
Constructor and destructor are called when the object is created and destroyed respectively. If an object is "destroyed", it means that no reference is made to the object. For example, variables that reference the object are deleted (unset), assigned a value again, or the script execution ends, the Destructor is called.
_ Construct ()
_ Construct () constructor is the most frequently used function so far. You can initialize an object in the constructor. You can define any number of parameters for the constructor as long as the corresponding number of parameters are input during instantiation. Any exceptions in the constructor will prevent object creation.
The Code is as follows:
Class Device {
Public function _ construct (Battery $ battery, $ name ){
$ This-> battery = $ battery;
$ This-> name = $ name;
$ This-> connect ();
}
}
In the preceding sample code, the Device class constructor assigns values to the member attributes and calls the connect () method.
The Code is as follows:
Declare the constructor as a private method to avoid object creation outside the class, which is often used in the single-profit mode.
_ Desctruct ()
A destructor is usually called when an object is destroyed. The Destructor does not receive any parameters. Cleaning is often performed in destructor, such as shutting down database connections.
Property Overloading)
One thing to note is that the "overload" in PHP is not the same as that in most other languages, although the same functions are implemented.
The two magic methods involved in attribute overloading are mainly used to process attribute access and define what happens when we try to access a non-existent (or inaccessible) attribute.
_ Get ()
Magic method _ get () is called when we try to access a nonexistent property. It receives a parameter, which indicates the name of the access attribute and returns the value of this attribute. In the above Device class, there is a data attribute, which plays a role here, as shown in 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 commonly used magic method is to expand access control by creating a "read-only" attribute. In the above Battery class, there is a private attribute $ charge. We can use the _ get () magic method to extend this attribute to be readable outside the class but cannot be modified. 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 attribute. It receives two parameters, one representing the attribute name and the other representing the attribute value. 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-> data [$ name] = $ value;
}
}
_ Isset ()
The _ isset () magic method is called when the isset () method is called for an inaccessible attribute. It receives a parameter to indicate the attribute name. It should return a Boolean value to indicate whether the attribute 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 attribute. It receives a parameter to express the attribute name.
Convert an object to a string
Sometimes we need to express 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 cocould not be converted to string
_ ToString ()
_ ToString () is called when we use an object as a string. It does not receive any parameters. This method allows us to define the object representation. 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)
Static magic method _ set_state (), which is called when we use the var_export () function to output an object. The var_export () function is used to convert PHP variables to PHP code. It receives an associated array containing the object property value 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;
}
//...
}
Clone object
By default, all objects are passed by reference. Therefore, when an object is assigned to another variable, a reference pointing to the object is created and the object is not copied. To truly copy 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, no object inside the object will be cloned. Therefore, the final result is that two objects share the same internal object. The sample code is as follows:
The Code is as follows:
$ Device = new Device (new Battery (), 'imagic ');
$ Device2 = clone $ device;
$ Device-> battery-> setCharge (65 );
Echo $ device2-> battery-> charge;
// 65
_ Clone ()
_ Clone () magic method _ clone () can solve the above problem. When you use the clone keyword for an object, this magic method is called. In this magic method, we can clone any sub-object. The Code is as follows:
The Code is as follows:
Class Device {
...
Public function _ clone (){
// Copy our Battery object
$ This-> battery = clone $ this-> battery;
}
...
}
Object serialization
Serialization refers to the process of converting arbitrary data into string format. Serialization is usually used to store the entire object into a database or write it into a file. When deserializing the stored data, we can get the object before serialization. However, not all data can be serialized, such as database connections. Fortunately, there is a magic solution that can help us solve this problem.
_ Sleep ()
The magic method _ sleep () is called when serialize () is called to serialize an object. It does not receive any parameters and should return an array containing all attributes that should be serialized. In this magic method, you can also perform some other operations.
Note that you do not need to perform any destructor in the function, because this may affect the running objects.
The sample code is as follows:
The Code is as follows:
Class Device {
Public $ name;
Public $ battery;
Public $ data = array ();
Public $ connection;
//...
Public function _ sleep (){
Return array ('name', 'battery', 'data ');
}
//...
}
_ Wakeup ()
Magic method _ wakeup () is called when deserializing stored objects. It does not receive any parameters or return any values. It can be used to process database connections or resources 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 overload
PHP also has two magic methods related to member Methods: _ call () and _ callStatic (). These two magic methods are similar to attribute overload methods.
_ Call ()
Magic method _ call () is called when a nonexistent or inaccessible method is called. It receives two parameters. One is the name of the called method and the other is an array containing function parameters. We can use this method to call functions with the same name in the sub-object.
In this example, pay attention to the call_user_func_array () function, which allows us to dynamically call a named function.
The sample code is as follows:
The Code is as follows:
Class Device {
//...
Public function _ call ($ name, $ arguments ){
// Make sure our child object has this method
If (method_exists ($ this-> connection, $ name )){
// Forward the call to our child object
Return call_user_func_array (array ($ this-> connection, $ name), $ arguments );
}
Return null;
}
//...
}
_ CallStatic ()
The magic method _ callStatic () has the same function as _ call (). The only difference is that this method is called when trying to access a static method that does not exist or is inaccessible. The sample code is as follows:
The Code is as follows:
Class Device {
//...
Public static function _ callStatic ($ name, $ arguments ){
// Make sure our 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;
}
//...
}
Use objects as functions
Sometimes we need to use objects as functions. Using an object as a function is similar to using other common functions.
_ Invoke () (PHP 5.3)
Magic method _ invoke () is called when you try to use an object as a function. Any parameter defined in this method will be used as a function parameter. The sample code is as follows:
The 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 it is very useful. However, for PHP version updates, this function is no longer recommended. Instead, it is replaced by the spl_auto_register () function.