Home  >  Article  >  Backend Development  >  Detailed explanation of PHP object-oriented magic methods (__tostring, __invoke)

Detailed explanation of PHP object-oriented magic methods (__tostring, __invoke)

易达
易达Original
2020-05-27 16:56:562760browse

Objectives of this article:

1. Understand the definition of magic methods in PHP

2. Understand the usage scenarios of __tostring() magic method

3. Master the usage of __tostring() magic method

4. Understand the usage scenarios of __invoke() magic method

5. Master the usage of __invoke() magic method

(1) Understand the definition of magic methods in PHP

PHP Reserve all class methods starting with __ (two underscores) as magic methods. Therefore, when defining class methods, except for the above magic methods, it is recommended not to prefix them with __.

(2) Understand the usage scenarios of the __tostring() magic method

When we need to convert an object into a string, we can define the __tostring method in the class, and then write our custom logic in it

(3) Master the magic method of __tostring() Usage

Summary:

1. The definition of the magic method __tostring method in the class, the definition format is as follows public function __tostring(), note that there are two underscores, not one

2. When the object is used as a String, this method will be automatically called

- For example, when we generally output a string, we use echo "Hello", so if we want to convert an object When used as String, we can also directly write echo $obj like this. At this time, this line of code will trigger the execution of the __tostring magic method

Each summary is passed It comes from practice. Now we use practice to demonstrate the summary. This can promote understanding and make each summary clearer and more intuitive.

##Case 1.

Practice goals:

1. In the class, The definition of the magic method __tostring method, the definition format is as follows public function __tostring(), note that there are two underscores, not one

The specific code is as follows:

<?php
class Animal{
    public $name = "";
    public function __construct($name){
        $this->name = $name;
    }
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法
    public function __tostring(){
        return "自动执行了Animal类中的__tostring方法<br/>";
    }
}
$monkey = new Animal("猴子");
?>

Case 2,

Practice goals:

##2. When the object is used as a String, this method will be automatically called

-for example We usually output strings using echo "Hello", so if we want to use an object as a String, we can also directly write echo $obj like this. At this time, this line of code will trigger the __tostring magic. Execution of the method

The specific code is as follows:

<?php
class Animal{
    public $name = "";
    public function __construct($name){
        $this->name = $name;
    }
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法
    public function __tostring(){
        return "自动执行了Animal类中的__tostring方法<br/>";
    }
}
$monkey = new Animal("猴子");
echo $monkey;
?>
The operation result is:

Automatic execution The __tostring method in the Animal class

我们发现其实我们没有手动的去调用__tostring方法,也就是说没有写成$monkey->__tostring(),但是这个方法依然执行了,因为什么呢?因为我们写了echo $monkey,所以相当于我们把$monkey对象当成了字符串来使用了,然后这个类中又定义了这个魔术方法,所以它就像魔术一样,突然就被自动执行了

这里一定要注意,是2个下划线,不是一个,否则就不是魔术方法了,下面还是再来做下测试

具体代码如下:

<?php
class Animal{
    public $name = "";
    public function __construct($name){
        $this->name = $name;
    }
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法 注意这里改成了一个下划线
    public function _tostring(){
        return "自动执行了Animal类中的__tostring方法<br/>";
    }
}
$monkey = new Animal("猴子");
echo $monkey;
?>

运行结果为:

Catchable fatal error: Object of class Animal could not be converted to string in D:\E-class\class-code\classing\index.php on line 19

所以此刻就会报错了,因为没有__tostring的魔术方法了,所以一定要注意是2个下划线,就好像构造函数和析构函数一样,都是两个下划线

(四)、了解__invoke()魔术方法的使用场景

当我们有需要将一个对象直接当成方法使用时,我们可以在类中定义__invoke方法,然后在里面写我们的自定义逻辑

(五)、掌握__invoke()的魔术方法的用法

总结:

1、类中__invoke魔术方法的定义如下:public function __invoke()其实和普通函数一样的定义,就是名称必须是__invoke

2、当对象被当做方法使用时,这个方法会被自动调用

    -比如我们一般调用方法是怎么调用的,是直接方法名(),比如smile()这样,所以当我们希望把一个对象当成方法使用时,应该怎么做呢?其实就是直接$obj(里面可以写参数),这样的形式就是方法调用的形式对吧,那么,一旦我们这样写$obj(参数),那么这个类中的__invoke()的魔术方法也会被自动的调用

每个总结都是通过实践得出来的,现在我们用实践来演示总结,这样可以促进理解,让每个总结理解起来更加清晰,直观

具体代码:

案例一、

实践目标:

1、类中__invoke魔术方法的定义如下:public function __invoke()其实和普通函数一样的定义,就是名称必须是__invoke

具体代码如下:

<?php
class Animal{
    public $name = "";
    public function __construct($name){
        $this->name = $name;
    }
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法
    public function __invoke(){
        return "自动执行了Animal类中的__invoke方法<br/>";
    }
}
$monkey = new Animal("猴子");

?>

案例二、

实践目标:

1、当对象被当做方法使用时,这个方法会被自动调用

    -比如我们一般调用方法是怎么调用的,是直接方法名(),比如smile()这样,所以当我们希望把一个对象当成方法使用时,应该怎么做呢?其实就是直接$obj(里面可以写参数),这样的形式就是方法调用的形式对吧,那么,一旦我们这样写$obj(参数),那么这个__invoke()的魔术方法也会自动的调用

具体代码如下:

<?php
class Animal{
    public $name = "";
    public function __construct($name){
        $this->name = $name;
    }
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法
    public function __invoke(){
        echo "自动执行了Animal类中的__invoke方法<br/>";
    }
}
$monkey = new Animal("猴子");
$monkey();

?>

运行结果如下:

自动执行了Animal类中的__invoke方法

我们发现其实我们没有手动的去调用__invoke方法,也就是说没有写成$monkey->__invoke(),但是这个方法依然执行了,因为什么呢?因为我们写了$monkey(),所以相当于我们把$monkey对象当成方法来使用了,然后这个类中又定义了这个魔术方法,所以它就像魔术一样,突然就被自动执行了

这里一定要注意,是2个下划线,不是一个,否则就不是魔术方法了,下面还是再来做下测试

<?php
class Animal{
    public $name = "";
    public function __construct($name){
        $this->name = $name;
    }
    public function eat(){

    }
    public function sleep(){

    }
    //魔术方法 只写一个_试下
    public function _invoke(){
        echo "自动执行了Animal类中的__invoke方法<br/>";
    }
}
$monkey = new Animal("猴子");
$monkey();

?>

运行结果如下:

Fatal error: Uncaught Error: Function name must be a string in D:\E-class\class-code\classing\index.php:19 Stack trace: #0 {main} thrown in D:\E-class\class-code\classing\index.php on line 19

所以一定要注意是2个下划线,不是一个,否则就不是魔术方法了

总结:

1、本文主要是讲解了2个魔术方法,__tostring,__invoke,并具体讲了他们的具体实现方式和使用场景

希望本文能给大家带来一定的帮助,谢谢!!!

The above is the detailed content of Detailed explanation of PHP object-oriented magic methods (__tostring, __invoke). For more information, please follow other related articles on the PHP Chinese website!

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