Home >Backend Development >PHP Tutorial >Exploring the Magic Methods in PHP_PHP Tutorial

Exploring the Magic Methods in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-13 17:18:55885browse

In object-oriented programming, PHP provides us with many magic methods. Flexible use of these magic methods can simplify many operations in our object-oriented development process. In PHP, magic methods usually start with two underscores (__). Different from ordinary methods (methods are also called functions) in PHP, magic methods are usually automatically called by the program under specific circumstances, while ordinary methods are usually called manually by us. Magic methods provide us with very useful functions. There are many magic methods in PHP. For details, you can refer to the PHP manual, which can be viewed here. In this article, I just briefly introduce some commonly used magic methods.
1. Preparation
In order to fully understand the concept of magic methods, we need to use these magic methods in the code. They are only conceptual things and will probably be forgotten after reading them once. So here we need to define two simple classes first.
Usually, we are used to defining each class in a separate file, and the class file is named in the form of "classname.class.php". Here we define two simple classes, one is the Device class and the other is the Battery class. The two classes defined are as follows:
File:Device.class.php

1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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;
        }
    }
?>
2 3 4 5 6
7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Battery{
private $charge=0;

public function setCharge($charge){
$charge=(int)$charge;
if($charge<0){
$charge=0;
}else{
$charge=100;
}
$this->charge=$charge;
        }
 
    }
?>
8 9 10 11 12 13 14 15 16 17 18
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;         } } ?>
File:Battery.class.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 class Battery{<🎜>           private $charge=0;<🎜> <🎜>          public function setCharge($charge){<🎜>                $charge=(int)$charge;<🎜>                    if($charge<0){<🎜>                    $charge=0;<🎜>                }else{<🎜>                     $charge=100;<🎜>             }<🎜>                  $this->charge=$charge;         } } ?>
In the Device class, four member attributes are defined, namely: name is used to represent the name of the device, battery is used to save a Battery object, data is defined as an array, and connection is used to save handles to external resources. In this class, two member methods connect() and disconnect() are also defined to establish and disconnect connections respectively.
In the Battery class, only a private property charge and a member method setCharge() are defined to set the value of charge.
The two classes defined here have no actual use, they are just to enable everyone to better understand the magic methods in PHP.
2. Constructor and destructor
Constructors and destructors are automatically called by the system when objects are created and destroyed.
1.Constructor:__construct()
The __construct function is by far the most used magic function. When the object is created, we can perform any initialization operations in the constructor, especially initialization of member variables. Any number of parameters can be defined for a constructor. If the constructor cannot be executed correctly for whatever reason, the creation of the object will fail. Below is an example of using constructor in Device class.
1
1
2
3
4
5
6
public function __construct($name,Battery $battery){
     //battery的值只能是由Battery类实例化的一个对象
    $this->battery=$battery;
    $this->name=$name;
    $this->connect();
}
2
3
4
5
1 $device=new Device('iPhone',$battery);
6
public function __construct($name,Battery $battery){ //The value of battery can only be an object instantiated by the Battery class $this->battery=$battery; $this->name=$name; $this->connect(); }
In this constructor, we specify two formal parameters for the constructor, assigning values ​​to the member attributes name and battery respectively, and also call the connect() function of the class in the constructor. Note: Declaring the constructor as a private method prevents the program from directly creating an instance object of the class outside the class. This is commonly used when implementing the singleton pattern of the design pattern.
With the constructor, we can instantiate an object of Device class like the following code.
1
2
3
public function __destruct(){
      $this->disconnect();
}
2.Destructor:__destruct() In contrast to constructors, destructors are automatically called by the system when an object is destroyed. The way to define a constructor in a class is as follows:
1 2 3 public function __destruct(){ $this->disconnect(); }
In this destructor, before the object is destroyed, the destructor first calls the disconnect() function in the class.
3. Attribute overloading
According to the description in the PHP manual, the "overloading" provided by PHP refers to dynamically "creating" class properties and methods. We do this through magic methods.
Overloaded methods will be called when calling class attributes or methods that are undefined or invisible in the current environment. In other words, overloaded methods will not be called when accessing methods or attributes that are accessible in a class. All overloaded methods must be declared public.
1.__get()
When reading the value of an inaccessible property, __get() is called.
2.__set()
When assigning a value to an inaccessible property, __set() is called.
3.__isset()
__isset() is called when isset() or empty() is called on an inaccessible property.
4.__unset()
When unset() is called on an inaccessible property, __unset() is called.
4. Convert the object to a string :__toString()
The __toString method is called when we try to treat the object as an ordinary string. For example, when we print an object, this function will be called automatically, such as: echo $object name. If the __toString method is not defined, PHP will return an error.
5. Clone object:__clone()
When we clone an object, the magic method __clone() will be automatically called
6. Object serialization
Serialization is the process of converting any data into string format. Through serialization, we can save a complete object in a file or in a database. One problem with serialization is that not all data can be serialized, such as a database connection.
1.__sleep()
When we use the serialize() function on an object, the __sleep() function will be called.
2.__wakeup()
When we use the unserialize() function on an object, the __wakeup() function will be called.
7. Method overloading
1.__call()
When an inaccessible method is called on an object, __call() is called.
2.__callStatic() (PHP 5.3)
When calling an inaccessible method in static mode, __callStatic() will be called.
8. Use objects as functions
1.__invoke
This method is called when we try to use the object as a function.
9. Automatic loading of classes
1.__autoload()
This method allows the program to automatically find the class file and load the class file into the current script when we instantiate a class, which can simplify a lot of our use of require.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/621604.htmlTechArticleIn object-oriented programming, PHP provides us with many magic methods. Flexible use of these magic methods can simplify We do many operations in the object-oriented development process. In PHP,...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn