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

function __constrct([parameter list]){

 

    Method implementation // usually assigns initial values to member variables.

 

}

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

<?php

    class Person

    {                                                                    

            public $name;      

            public $age;      

            public $sex;      

 

        /**

         * Explicitly define the construction method containing the reference

         */                                                                                      

        public function __construct($name="", $sex="Male", $age=22)

        {    

            $this->name = $name;

            $this->sex = $sex;

            $this->age = $age;

        }

 

        /**

         * say Method Definition

         */

        public function say()

        {

            echo "Name:" . $this->name . ",Sex:" . $this->sex . ",Age:" . $this->age;

        }  

 

    }

Create $Person1 object without reference.

1

2

$Person1 = new Person();

echo $Person1->say(); //Name:,Sex:Male,Age:22

Create $Person2 object with one parameter "Jams" call.

1

2

$Person2 = new Person("Jams");

echo $Person2->say(); //Name: Jams, Sex: Male, Age: 22

Create a $Person3 object with a 3-argument call.

1

2

$Person3 = new Person ("Jack", "Male", 25);

echo $Person3->say(); //Name: Jack, Sex: Male, Age: 25

__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

function __destruct()

{

    //method body

}

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

<?php

class Person{    

 

    public $name;        

    public $age;        

    public $sex;        

 

    public function __construct($name="", $sex="Male", $age=22)

    {  

        $this->name = $name;

        $this->sex  = $sex;

        $this->age  = $age;

    }

 

    /**

     * say method

     */

    public function say()

    {

        echo "Name:".$this->name.",Sex:".$this->sex.",Age:".$this->age;

    }  

 

    /**

     * declare a destructor method

     */

    public function __destruct()

    {

            echo "Well, my name is ".$this->name;

    }

}

 

$Person = new Person("John");

unset($Person); //destroy the object of $Person created above

Output results

1

Well, my name is John

__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

function __call(string $function_name, array $arguments)

{

    // method body

}

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

<?php

class Person

{                            

    function say()

    {

           echo "Hello, world!<br>";

    }    

 

    function __call($funName, $arguments)

    {

          echo "The function you called:" . $funName . "(parameter:" // Print the method's name that is not existed.

          print_r($arguments); // Print the parameter list of the method that is not existed.

          echo ")does not exist!!<br>\n";                  

    }                                        

}

$Person = new Person();          

$Person->run("teacher"); // If the method which is not existed is called within the object, then the __call() method will be called automatically.

$Person->eat("John", "apple");            

$Person->say();

Show results

1

2

3

The function you called: run (parameter: Array([0] => teacher)) does not exist!

The function you called: eat (parameter: Array([0] => John[1] => apple)) does not exist!

Hello world!

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

<?php

class Person

{

    function say()

    {

        echo "Hello, world!<br>";

    }

 

    public static function __callStatic($funName, $arguments)

    {

        echo "The static method you called:" . $funName . "(parameter:" ;  // Print out the undefined method name.

        print_r($arguments); // Print out the list of parameters of the undefined method.

        echo ")does not exist!<br>\n";

    }

}

$Person = new Person();

$Person::run("teacher"); // If a method that does not exist within this project is called, then the __callStatic() method will be called automatically.

$Person::eat("John", "apple");

$Person->say();

The execution results are as follows:

1

2

3

The static method you called: run (parameter: Array([0] => teacher)) does not exist!

The static method you called: eat (parameter: Array([0] => John[1] => apple)) does not exist!

Hello world!

__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

<?php

class Person

{

    private $name;

    private $age;

 

    function __construct($name="", $age=1)

    {

        $this->name = $name;

        $this->age = $age;

    }

 

    public function __get($propertyName)

    {  

        if ($propertyName == "age") {

            if ($this->age > 30) {

                return $this->age - 10;

            } else {

                return $this->$propertyName;

            }

        } else {

            return $this->$propertyName;

        }

    }

}

$Person = new Person("John", 60);   // Instantiate the object with the Person class and assign initial values to the properties with the constructor.

echo "Name:" . $Person->name . "<br>";   // When the private property is accessed, the __get() method will be called automatically,so we can get the property value indirectly.

echo "Age:" . $Person->age . "<br>";    // The __get() method is called automatically,and it returns different values according to the object itself.

The results are shown below

1

2

Name: John

Age: 50

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

<?php

class Person

{

    private $name;

    private $age;

 

    public function __construct($name=""$age=25)

    {

        $this->name = $name;

        $this->age  = $age;

    }

 

    public function __set($property, $value) {

        if ($property=="age")

        {

            if ($value > 150 || $value < 0) {

                return;

            }

        }

        $this->$property = $value;

    }

 

    public function say(){

        echo "My name is ".$this->name.",I'm ".$this->age." years old";

    }

}

 

$Person=new Person("John", 25); //Note that the class is initialized and initial values are assigned to "name" and "age".

$Person->name = "Lili";     // The "name" property value was successfully modified. If there is no __set() method, the program will report an error.

$Person->age = 16; // The "age" attribute was modified successfully.

$Person->age = 160; //160 is an invalid value, so the modification fails.

$Person->say();  

Code run results:

1

My name is Lili, I'm 16 years old

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:

  1. If the parameter is a public attribute, you can use the isset() method to determine if the attribute is set.
  2. 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

<?php

class Person

{

    public $sex;

    private $name;

    private $age;

 

    public function __construct($name=""$age=25, $sex='Male')

    {

        $this->name = $name;

        $this->age  = $age;

        $this->sex  = $sex;

    }

 

    /**

     * @param $content

     *

     * @return bool

     */

    public function __isset($content) {

        echo "The {$content} property is private,the __isset() method is called automatically.<br>";

        echo  isset($this->$content);

    }

}

 

$person = new Person("John", 25); // Initially assigned.

echo isset($person->sex),"<br>";

echo isset($person->name),"<br>";

echo isset($person->age),"<br>";

The code runs as follows:

1

2

3

4

5

1

The name property is private,the __isset() method is called automatically.

1

The age property is private,the __isset() method is called automatically.

1

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

<?php

class Person

{

    public $sex;

    private $name;

    private $age;

 

    public function __construct($name=""$age=25, $sex='Male')

    {

        $this->name = $name;

        $this->age  = $age;

        $this->sex  = $sex;

    }

 

    /**

     * @param $content

     *

     * @return bool

     */

    public function __unset($content) {

        echo "It is called automatically when we use the unset() method outside the class.<br>";

        echo  isset($this->$content);

    }

}

 

$person = new Person("John", 25); // Initially assigned.

unset($person->sex),"<br>";

unset($person->name),"<br>";

unset($person->age),"<br>";

The result of running the code is as follows:

1

2

3

4

It is called automatically when we use the unset() method outside the class.

1

It is called automatically when we use the unset() method outside the class.

1

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

<?php

class Person

{

    public $sex;

    public $name;

    public $age;

 

    public function __construct($name=""$age=25, $sex='Male')

    {

        $this->name = $name;

        $this->age  = $age;

        $this->sex  = $sex;

    }

 

    /**

     * @return array

     */

    public function __sleep() {

        echo "It is called when the serialize() method is called outside the class.<br>";

        $this->name = base64_encode($this->name);

        return array('name', 'age'); // It must return a value of which the elements are the name of the properties returned.

    }

}

 

$person = new Person('John'); // Initially assigned.

echo serialize($person);

echo '<br/>';

The code runs as follows:

1

2

It is called when the serialize() method is called outside the class.

O:6:"Person":2:{s:4:"name";s:8:"5bCP5piO";s:3:"age";i:25;}

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

<?php

class Person

{

    public $sex;

    public $name;

    public $age;

 

    public function __construct($name=""$age=25, $sex='Male')

    {

        $this->name = $name;

        $this->age  = $age;

        $this->sex  = $sex;

    }

 

    /**

     * @return array

     */

    public function __sleep() {

        echo "It is called when the serialize() method is called outside the class.<br>";

        $this->name = base64_encode($this->name);

        return array('name', 'age'); // It must return a value of which the elements are the name of the properties returned.

    }

 

    /**

     * __wakeup

     */

    public function __wakeup() {

        echo "It is called when the unserialize() method is called outside the class.<br>";

        $this->name = 2;

        $this->sex = 'Male';

        // There is no need to return an array here.

    }

}

 

$person = new Person('John'); // Initially assigned.

var_dump(serialize($person));

var_dump(unserialize(serialize($person)));

The code runs as follows:

1

2

3

4

It is called when the serialize() method is called outside the class.

string(58) "O:6:"Person":2:{s:4:"name";s:8:"5bCP5piO";s:3:"age";i:25;}"

It is called when the unserialize() method is called outside the class.

object(Person)#2 (3) { ["sex"]=> string(3) "Male" ["name"]=> int(2) ["age"]=> int(25) }

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

<?php

class Person

{

    public $sex;

    public $name;

    public $age;

 

    public function __construct($name=""$age=25, $sex='Male')

    {

        $this->name = $name;

        $this->age  = $age;

        $this->sex  = $sex;

    }

 

    public function __toString()

    {

        return  'go go go';

    }

}

 

$person = new Person('John'); // Initially assigned.

echo $person;

The result of running the code is as follows:

1

go go go

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

<?php

class Person

{

    public $sex;

    public $name;

    public $age;

 

    public function __construct($name=""$age=25, $sex='Male')

    {

        $this->name = $name;

        $this->age  = $age;

        $this->sex  = $sex;

    }

 

}

 

$person = new Person('John'); // Initially assigned.

echo $person;

The result of running the code is as follows:

1

Catchable fatal error: Object of class Person could not be converted to string in D:\phpStudy\WWW\test\index.php on line 18

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

<?php

class Person

{

    public $sex;

    public $name;

    public $age;

 

    public function __construct($name=""$age=25, $sex='Male')

    {

        $this->name = $name;

        $this->age  = $age;

        $this->sex  = $sex;

    }

 

    public function __invoke() {

        echo 'This is an object';

    }

 

}

 

$person = new Person('John'); // Initially assigned.

$person();

The result of running the code is as follows:

1

This is an object

If you insist on using the object as a method (but do not define the __invoke() method), you will get the following result:

1

Fatal error: Function name must be a string in D:\phpStudy\WWW\test\index.php on line 18

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

<?php

class Person

{

    public $sex;

    public $name;

    public $age;

 

    public function __construct($name=""$age=25, $sex='Male')

    {

        $this->name = $name;

        $this->age  = $age;

        $this->sex  = $sex;

    }

 

}

 

$person = new Person('John'); // Initially assigned.

var_export($person);

The result of executing the code is as follows:

1

Person::__set_state(array( 'sex' => 'Male', 'name' => 'John', 'age' => 25, ))

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

<?php

class Person

{

    public $sex;

    public $name;

    public $age;

 

    public function __construct($name=""$age=25, $sex='Male')

    {

        $this->name = $name;

        $this->age  = $age;

        $this->sex  = $sex;

    }

 

    public static function __set_state($an_array)

    {

        $a = new Person();

        $a->name = $an_array['name'];

        return $a;

    }

 

}

 

$person = new Person('John'); // Initially assigned.

$person->name = 'Jams';

var_export($person);

The result of executing the code is as follows:

1

Person::__set_state(array( 'sex' => 'Male', 'name' => 'Jams', 'age' => 25, ))

14. __clone()

在In PHP, we can clone objects using the clone keyword with the following syntax:

1

$copy_of_object = clone $object;

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

<?php

class Person

{

    public $sex;

    public $name;

    public $age;

 

    public function __construct($name=""$age=25, $sex='Male')

    {

        $this->name = $name;

        $this->age  = $age;

        $this->sex  = $sex;

    }

 

    public function __clone()

    {

        echo __METHOD__."your are cloning the object.<br>";

    }

 

}

 

$person = new Person('John'); // Initially assigned.

$person2 = clone $person;

 

var_dump('persion1:');

var_dump($person);

echo '<br>';

var_dump('persion2:');

var_dump($person2);

运行代码结果如下:

1

2

3

Person::__clone your are cloning the object.

string(9) "persion1:" object(Person)#1 (3) { ["sex"]=> string(3) "Male" ["name"]=> string(6) "John" ["age"]=> int(25) }

string(9) "persion2:" object(Person)#2 (3) { ["sex"]=> string(3) "Male" ["name"]=> string(6) "John" ["age"]=> int(25) }

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

/**

 * file non_autoload.php

 */

 

require_once('project/class/A.php');

require_once('project/class/B.php');

require_once('project/class/C.php');

.

.

.

 

if (ConditionA) {

    $a = new A();

    $b = new B();

    $c = new C();

    // …

} else if (ConditionB) {

    $a = newA();

    $b = new B();

    // …

}

那么,如果我们使用__autoload()方法呢?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

/**

 * file autoload_demo.php

 */

function  __autoload($className) {

    $filePath = “project/class/{$className}.php”;

    if (is_readable($filePath)) {

        require($filePath);

    }

}

 

if (ConditionA) {

    $a = new A();

    $b = new B();

    $c = new C();

    // …

} else if (ConditionB) {

    $a = newA();

    $b = new B();

    // …

}

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

<?php

class C {

    private $prop;

 

    public function __construct($val) {

        $this->prop = $val;

    }

 

    /**

     * @return array

     */

    public function __debugInfo() {

        return [

            'propSquared' => $this->prop ** 2,

        ];

    }

}

 

var_dump(new C(42));

Implementation results:

1

object(C)#1 (1) { ["propSquared"]=> int(1764) }

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.

Related articles

How to split a string into an array in php

In php, you can use the str_split() function to split a string into an array, which splits the string into several substrings of the desired length and combines them into an array; syntax "str_split(string,length)".

php crop image steps

php crop image steps: 1, create a PHP sample file; 2, use "function imageCropper(){...}" method to achieve the image does not change the cropping; 3, through the "function imageZoom (){...}" method to achieve proportional cropping of the image.

How to replace alt with php regular?

php regular to achieve the replacement alt method: 1, create a PHP sample file; 2, get the content to be replaced; 3, through "<img.*?src=[\"|\'](. *?) [\"|\']. *? >" can be replaced by the regular implementation.

How to convert svg to svg in php?

php svg to jpg method: 1, create a PHP sample file; 2, by "public function svgtojpg(){$image =...}" method to achieve the conversion.

Two basic output methods for php

The two basic output methods of php are "echo" and "print". echo is used to output one or more strings, which can take multiple arguments and have no return value, with the syntax "echo($ str)"; and print is used to output a string that can only take one

How to display a mess of php images?

php image display a mess of solutions: 1, open the corresponding PHP code file; 2, in the page header plus "header ("Content-Type: image/jpg");" code to declare the image type can be.

php can't load js css

php can not load js css solution: 1, check the correct path to load; 2, prohibit the use of absolute path; 3, use relative path to load the file can be.

php how to check user ip

php query user ip method: 1, get user ip by "$_SERVER["REMOTE_ADDR"]" way; 2, get user ip by "($user_IP) ? $user_IP : $_SERVER["REMOTE_ADDR"];" to get the user ip and so on.

How to invert a string by word in php

Inversion methods: 1. use "explode(' ',$str)" statement to convert string to array; 2. use "array_reverse($arr)" statement to invert the array and return the array in the reverse order of elements; 3. use "implode(' ',$arr)" statement to convert the inver

php get maximum value in several numbers

In php, you can use the max() function to get the maximum value among several numbers. The function works by calculating and returning the maximum value among several specified values, with the syntax "max(value1,value2,...) ;".