php -- 魔术方法 之 对象输出 : __toString()

时间:2023-03-09 14:29:15
php -- 魔术方法 之 对象输出 : __toString()

对象输出:__toString()

当一个对象被当做字符串进行输出时(echo,print),会调用__toString()方法

<?php

    //输出对象
class Person{
//属性
public $name;
private $age; //方法
public function __construct($name,$age){
$this->name = $name;
$this->age = $age;
} public function setAge($age){
$this->age = $age;
} public function getAge(){
return $this->age;
} //对象转字符串方法
//要求只能返回字符串类型的数据
public function __toString(){
//将需要输出的对象的属性返回即可
//组织语言进行输出(控制属性的输出)
return (string)($this->name . ':' . $this->age);
}
} //实例化
$person = new Person('周芷若',);
//var_dump($person); //echo $person; //对象不能被当做字符串输出 //需求:echo 对象,输出对象里面的所有属性(所有的属性连接成一个字符串)
echo $person;