Common magic Methods in PHP function and usage examples
This article mainly introduces the function and usage examples of common magic methods in PHP, this article explains the constructors and destructors __construct () and __desctruct () and property overloading (properties overloading) __get () and, __ Set (), __isset () and so on magic method, need friends can refer to the next
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 is set off by a particular condition. 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:
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 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.
The code is as follows:
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 ()
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 outside of 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 ()
__set () The Magic method is called when we try to modify an inaccessible property, it 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->data[$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:
The code is 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 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:
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 ()
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:
The code is as follows:
Class Device {
//...
Public Function __call ($name, $arguments) {
Make sure our child object have 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 ()
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:
Copy the code code as follows:
Class Device {
//...
public static function __callstatic ($name, $arguments) {
Make sure our class have 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'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:
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 this method is very useful. However, for updates to the PHP version, the function is not recommended and is replaced by the Spl_auto_register () function.
http://www.bkjia.com/PHPjc/1025336.html www.bkjia.com true http://www.bkjia.com/PHPjc/1025336.html techarticle examples of functions and usages of common magic methods in PHP this article mainly introduces the function and usage examples of common magic methods in PHP, this article explains the constructors and destructors _ ...