【问题标题】:How to use php __toString如何使用 php __toString
【发布时间】:2015-10-11 15:21:45
【问题描述】:

__toString在PHP中有什么用处?

例如,我有一个函数,例如(在一个名为 person 的类中)

public function __construct($id, $name) {

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

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

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

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

如何使用__toString 获取这些数据并将它们打印在一行上。

例如: 12 测试说明詹姆斯测试图片

【问题讨论】:

    标签: php oop


    【解决方案1】:

    __toString() 方法用于如果您尝试回显对象实例而不是简单地回显该对象的属性。通常会抛出异常,但是 to_string 方法定义了一个响应

    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;
    

    __toString() 返回将被回显的值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-11
      • 1970-01-01
      • 2010-09-28
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 2011-07-07
      相关资源
      最近更新 更多