How to use php __toString

2020-05-10 07:48发布

What are the uses of __toString in PHP?

For example I have a function such as (inside a class called person)

public function __construct($id, $name) {

       $this->id = $id;
       $this->name= $name;
  }

and

$person= new person("12","James");

$person->setDescription("Test Description");

$person->setImage("Test Image");

How can I use __toString to grab this data and print them on one line.

For example: 12 Test Description James Test Image

标签: php oop
1条回答
Summer. ? 凉城
2楼-- · 2020-05-10 08:14

The __toString() method is used if you try to echo an object instance rather than simply properties of that object. Normally that would throw an exception, but the to_string method defines a response

class person{
    public function __construct($id, $name) {
        $this->id = $id;
        $this->name= $name;
    }
    public function __toString() {
        return $this->id . ' ' . $this->name;
    }
}

$person= new person("12","James");
echo $person;

The __toString() returns the value that will be echoed

查看更多
登录 后发表回答