PHP __toString()不能正常工作?

时间:2017-03-24 10:24:14

标签: php oop

我正在尝试学习PHP面向对象编程,但在视频教程中,我收到错误,而教程演示者没有同样的问题!

PHP代码

<?php


class Player {

public $score = 10;
public $name = "";

public function __construct($score,$name) {

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

public function __destruct() {

    echo "Object With Name ".$this->name." has been destroyed";
}

public function __toString() {
    echo "The Object with name ".$this->name." has been echoed</br>";
}

}


$newPlayer = new Player(50,"Ahmad");


echo $newPlayer;


?>

我收到以下错误:

The Object with name Ahmad has been echoed
Catchable fatal error: Method Player::__toString() must return a string value in D:\xampp\htdocs\php_oop\index.php on line 30

当我将echo更改为return时,我得到以下输出,这不应该发生,因为我没有取消设置对象。当__destruct()中的echo更改为return时,为什么会调用toString()函数?

错误变为:

The Object with name Ahmad has been echoed
Object With Name Ahmad has been destroyed

2 个答案:

答案 0 :(得分:5)

您需要添加return语句。

return "The Object with name ".$this->name." has been echoed</br>";

您的脚本在此文件的末尾结束,这就是调用析构函数的原因!

答案 1 :(得分:1)

正确答案如上:

return "The Object with name ".$this->name." has been echoed</br>";

完成对象后调用Destruct方法。在你的情况下:

echo $newPlayer;