Home  >  Article  >  Backend Development  >  Detailed explanation of __toString() method in PHP

Detailed explanation of __toString() method in PHP

藏色散人
藏色散人Original
2019-07-24 14:00:4810871browse

__toString(), the response method when the class is treated as a string

Function:

__toString() method is used for a class How to respond when it is treated as a string. For example what `echo $obj;` should display.

Note:

This method must return a string, otherwise a fatal error of level `E_RECOVERABLE_ERROR` will be issued.

Warning:

Cannot throw exceptions in the __toString() method. Doing so will result in a fatal error.

Code:

name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    public function __toString()
    {
        return  'go go go';
    }
}
$person = new Person('小明'); // 初始赋值
echo $person;

Result:

go go go

So what happens if there is no __toString() magic method in the class? Let’s test it:

Code:

name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    
}
$person = new Person('小明'); // 初始赋值
echo $person;

Result:

Catchable fatal error: Object of class Person could not be converted to string in D:\phpStudy\WWW\test\index.php on line 18
很明显,页面报了一个致命错误,这是语法所不允许的。

The above is the detailed content of Detailed explanation of __toString() method in PHP. 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