【问题标题】:PHP Error: Class::__toString() must return a string value inPHP 错误:Class::__toString() 必须返回一个字符串值
【发布时间】:2017-01-31 18:08:22
【问题描述】:

这是我尝试在 PHP 类中使用的 __toString() 方法。它抛出错误“Catchable fatal error: Method Project::__toString() must return a string value in...”

但据我所知,我传递给它的所有内容都是一个字符串。我什至检查了$this->proj_idgettype($var) 以确认它是一个字符串,它确实是。

这是项目类...

class Project {
  public $proj_id;
  public $proj_num;
  public $proj_name;

  public function __construct($id, $num, $name){
    $this->proj_id = $id;
    $this->proj_num = $num;
    $this->proj_name = $name;
  }

  public function __toString(){
    echo "<table>";
    echo "<tr><td>".'proj_id: '."</td><td> ".$this->proj_id." </td><t/r>";
    echo "</table><br><br>";
  }
}

这里是对象实例化...

$test_obj = new Project('XC2344','HKSTEST','Test Project');
echo $test_obj; //this is where the error shows up - even though it actually outputs the table with the correct value in both cells ?!

它实际上按照我的意愿输出表格和单元格以及这些单元格中的值,但随后给出错误并停止创建网页的其余部分。没看懂。

【问题讨论】:

  • return !== echo

标签: php oop tostring


【解决方案1】:

当您在 Project 对象上调用 echo 时,该对象将转换为将用于输出的字符串。如果你自己定义 __toString 方法,它必须返回一个必须输出的字符串。不要在 __toString 方法中立即输出字符串,而是直接返回它。

public function __toString(){
    return "<table>" .
           "<tr><td>".'proj_id: '."</td><td> ".$this->proj_id." </td><t/r>" .
           "</table><br><br>";
}

所以当你打电话时

echo $test_obj;

__toString 会被调用,你的函数会返回字符串,然后 echo 会输出它。

【讨论】:

    【解决方案2】:

    __toString() 必须返回一个字符串,而不是 echo 它:

    public function __toString(){
        return "<table>"
              . "<tr><td>".'proj_id: '."</td><td> ". $this->proj_id. " </td><t/r>"
              . "</table><br><br>"
    }
    

    【讨论】:

      【解决方案3】:

      回显不是字符串的唯一用途。也许您想将对象保存到数据库中,或者将其放入 JSON 结构中。

      __toString 必须返回一个字符串,而不是输出内容。

        public function __toString(){
          $str = "<table>";
          $str .= "<tr><td>".'proj_id: '."</td><td> ".$this->proj_id." </td><t/r>";
          $str .= "</table><br><br>";
      
          return $str;
        }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-01
        • 1970-01-01
        • 2018-05-15
        • 1970-01-01
        • 2013-12-04
        • 2020-06-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多