In PHP, methods named starting with a double underscore (__) are called magic methods in PHP, and they play a very important role in PHP. Magic methods include:
Method name | Description |
---|---|
__construct() | Constructor of class |
__destruct() | Destructor of a class |
__call($funName, $arguments) | The __call() method will be called when an undefined or unreachable method is called. |
__callStatic($funName, $arguments) | The __callStatic() method will be called when an undefined or unreachable static method is called. |
__get($propertyName) | The __get() method is called when a member variable of a class is retrieved. |
__set($property, $value) | The __set() method will be called when assigning a member variable of a class. |
__isset($content) | The __isset() method will be called when isset() or empty() is called to assign a value to an undefined or unreachable member. |
__unset($content) | The __unset() method will be called when reset() is called to update an undefined or unreachable member. |
__sleep() | When serialize() is executed, the __sleep() method will be called first. |
__wakeup() | The __wakeup() method will be called first when deserialization() is executed. |
__toString() | The __toString() method is called first when the display object is output directly using the echo method. |
__invoke() | When accessing an object using a function, the __invoke() method will be called first. |
__set_state($an_array) | The __set_state() method will be called when the var_export() method is called. |
__clone() | The __clone() method will be called when the object is copied and assigned. |
__autoload($className) | Called when trying to load an undefined class. |
__debugInfo() | Output debug information. |
This article will use some examples to demonstrate the use of PHP magic methods.
1.__construct()
The constructor method of a PHP class is the first method to be called when an object is created. Every class has a constructor method. If you don't define it explicitly in the class declaration, there will be a default unreferenced class constructor present, although it will not appear in the class definition.
1) Application of construction methods
Class constructors are usually used to perform some initialization tasks, such as assigning values to members for initialization when an object is created.
2) Declaration format of constructor methods in classes
1 2 3 4 5 |
|
Note: Only one constructor method can be declared in most classes. Because of this, PHP does not support constructor overloading.
Here is a complete example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
Create $Person1 object without reference.
1 2 |
|
Create $Person2 object with one parameter "Jams" call.
1 2 |
|
Create a $Person3 object with a 3-argument call.
1 2 |
|
__destruct()
A destructor is the opposite of a constructor.
A destructor allows you to perform some actions before destroying the object, such as closing the file, emptying the result set, etc.
The destructors are a new feature introduced in PHP 5.
The declaration of a destructor is similar to that of a constructor, starting with two underscores, and the name is fixed to __destruct().
Declarations of destructors
1 2 3 4 |
|
The destructor cannot take arguments.
Use of destructors
A destructor is generally not common in a class. It is an optional part of the class and is usually used to complete some cleanup tasks before the class is destroyed.
Here is an example of using a destructor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
Output results
1 |
|
__call()
The method accepts two parameters. The first parameter is the name of the undefined method, and the second parameter is an array of parameters passed to the method
Use
1 2 3 4 |
|
The __call() method will be called when an undefined method is called in the program.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Show results
1 2 3 |
|
4. __callStatic()
The __callStatic() method will be called automatically when an undefined static method is called in the program.
The usage of __callStatic() is similar to that of __call(). Here's an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
The execution results are as follows:
1 2 3 |
|
__get()
When you try to access an object's private properties externally, the application will throw an exception and end. We can solve this problem by using the __get method. This method gets the value of the private property from outside the object. Here is an example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
The results are shown below
1 2 |
|
6. __set()
The set($property,$value) method is used to set the private properties of a class. After assigning an undefined property, the set() method will be triggered and the parameters passed are the name and value of the property to be set.
Here is the demo code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
|
Code run results:
1 |
|
7. __isset()
Before using the __isset() method, let me explain the usage of the isset() method. isset() method is mainly used to determine if this variable is set.
If the isset() method is used outside the object, there are two cases:
- If the parameter is a public attribute, you can use the isset() method to determine if the attribute is set.
- If the parameter is a private property, the isset() method will not work.
So for private properties, is there any way to know if it's set or not? Of course, you can use the __isset() method outside the class to determine if a private property is set, as long as you define the __isset() method in the class.
The __isset() method is called when isset() or empty() is called on an undefined or inaccessible property. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
The code runs as follows:
1 2 3 4 5 |
|
8. __unset()
Similar to the isset() method, the unset() method will be called when called on an undefined or inaccessible property. Here is an example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
The result of running the code is as follows:
1 2 3 4 |
|
9. __sleep()
The serialize() method will check if there is a magic method __sleep() in the class. If present, the method will be called first and then the serialization operation will be performed.
The __sleep() method is usually used to specify the properties that need to be serialized before saving the data. You may find this function useful if there are some very large objects that do not need to be saved in their entirety.
For more information, please refer to the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
|
The code runs as follows:
1 2 |
|
10. __wakeup()
In contrast to the sleep() method, the wakeup() method is typically used for deserialization operations, such as rebuilding a database connection or performing other initialization operations.
The following are relevant examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
|
The code runs as follows:
1 2 3 4 |
|
11. __toString()
The __toString() method will be called when printing objects directly using the echo method.
Note: This method must return a string, otherwise it will raise a fatal error at the E_RECOVERABLE_ERROR level. And you cannot throw an exception in the __toString() method either.
Here is a related example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
The result of running the code is as follows:
1 |
|
So, what if the __toString() method is not defined in the class? Let's try it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
The result of running the code is as follows:
1 |
|
Apparently, it reports a fatal error on the page, and the PHP syntax does not support such writing.
12. __invoke()
The __ invoke() method will be called automatically when you try to call the object in the same way you call the function.
Note: This feature is only available in PHP 5.3.0 and higher.
The following are relevant examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
|
The result of running the code is as follows:
1 |
|
If you insist on using the object as a method (but do not define the __invoke() method), you will get the following result:
1 |
|
13.__set_state()
Starting with PHP 5.1.0, the __set_state() method is automatically called when calling var_export() to export class code.
The argument to the __set_state() method is an array of all property values in the format array('property' => value, ...)
In the following example, we do not define the __set_state() method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
|
The result of executing the code is as follows:
1 |
|
Obviously, the object's properties are printed.
Now let's look at another case of defining the __set_state() method:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
|
The result of executing the code is as follows:
1 |
|
14. __clone()
在In PHP, we can clone objects using the clone keyword with the following syntax:
1 |
|
However, using the clone keyword is only a shallow copy, since all referenced properties will still point to the original variable.
If the clone() method is defined in the object, the clone() method will be called in the object generated by the copy, and this method can be used to modify the value of the property (if necessary).
Here is a related example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
|
运行代码结果如下:
1 2 3 |
|
15.__autoload()
The __autoload() method can attempt to load undefined classes.
In the past, if you wanted to create 100 objects in a program file, you had to use include() or require() to include 100 class files, or you had to define 100 classes in the same class file. For example the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
|
那么,如果我们使用__autoload()方法呢?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
|
When the PHP engine uses class A for the first time, if class A is not found, the autoload method will be called automatically and the class name " A " will be passed as an argument. So what we need to do in the autoload() method is to find the appropriate class file based on the class name and include it. If the file is not found, then the php engine will throw an exception.
16. __debugInfo()
The __debugInfo() method is called automatically when the var_dump() method is executed. If the __debugInfo() method is not defined, then the var_dump method may print out all the properties of the object.
Examples:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
Implementation results:
1 |
|
Note: The __debugInfo() method should be used in PHP 5.6.0 and above.
Summary
These are the PHP magic methods that I know of, the common ones include __set() and __get() and __autoload(). If you have any other questions, you can get more help from the official PHP website.