Home > Backend Development > PHP Tutorial > Detailed explanation of magic method ___toString() instance (php advanced object-oriented tutorial)

Detailed explanation of magic method ___toString() instance (php advanced object-oriented tutorial)

巴扎黑
Release: 2023-03-07 14:50:01
Original
2203 people have browsed it

We all know that after we instantiate a class, when accessing the properties of the class, we always access them in the format of $instantiation name->property name. So have you ever directly output the object using echo or print? Try the results. Some people say that this should not work, and an error will be reported. Yes, such direct output will indeed report an error, but when we use the magic method __toString, it will be fine. The __toString() method will first convert the object into a string before outputting it, so that it can be output using echo or print.

Instance analysis:

<?php
header("content-type:text/html;charset=utf-8");
class Preson{
public $name;
private $age;
function __construct($name,$age)
{
$this->name = $name;
$this->age = $age;
}
public function __toString()
{
return $this->name . &#39;今年已经&#39; . $this->age . &#39;岁了&#39;;
}
}
$preson = new Preson(&#39;小明&#39;,18);
echo $preson;
Copy after login

Code analysis:

We first create a human class, define attributes, create a constructor, then we instantiate this class, and finally directly echo the class name. You will find that the error message will be displayed on the page: Object of class Preson could not be converted to string in D:\WWW\tostring.php on line 15. It means that the object's class cannot be converted to a string and cannot be output. So we just add the __toString() method, and just return the required results directly in the method.

The above is the detailed content of Detailed explanation of magic method ___toString() instance (php advanced object-oriented tutorial). For more information, please follow other related articles on the PHP Chinese website!

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