简体   繁体   中英

PHP __toString() Not working properly?

I am trying to learn PHP Objected Oriented Programming but during the video tutorial, I am getting an error while the tutorial presenter does not have the same issue!

PHP Code :

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


?>

I am getting following error:

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

When I change echo to return I get the following output which should not be happening as I am not unsetting the object. Why would the __destruct() function be called when echo is changed to return in the toString() ?

The error becomes:

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

You need to add return statement.

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

Your script ends at the end of this file, That's why destructor is called!

The right answer is like one above:

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

Destruct method is called when you are done with your object. In your case after:

echo $newPlayer;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM