Detailed explanation of __toString() method in PHP

藏色散人
Release: 2023-04-07 06:38:01
Original
11049 people have browsed it

__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:

<?php
class Person
{
    public $sex;
    public $name;
    public $age;
    public function __construct($name="",  $age=25, $sex=&#39;男&#39;)
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    public function __toString()
    {
        return  &#39;go go go&#39;;
    }
}
$person = new Person(&#39;小明&#39;); // 初始赋值
echo $person;
Copy after login

Result:

go go go
Copy after login

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

Code:

<?php
class Person
{
    public $sex;
    public $name;
    public $age;
    public function __construct($name="",  $age=25, $sex=&#39;男&#39;)
    {
        $this->name = $name;
        $this->age  = $age;
        $this->sex  = $sex;
    }
    
}
$person = new Person(&#39;小明&#39;); // 初始赋值
echo $person;
Copy after login

Result:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template