PHP Error: Class::__toString() must return a string value in

PHP Error: Class::__toString() must return a string value in

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

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

这是项目 class...

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 ?!

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

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

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

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

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

所以当你打电话时

echo $test_obj;

将调用 __toString,您的函数将 return 字符串,然后 echo 将输出它。

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

__toString必须return一个字符串,不输出内容

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

    return $str;
  }