简体   繁体   中英

PHP toString() not working

I am following a udemy course where we learnt toString, however on my browser it displays nothing when I use the toString function.

<?php 

class Baddie{

    //property
    public $evilness = 10;
    public $name = "";

    //constructor
    public function __construct($evilness, $name){
        //echo "A ". __CLASS__ . " has been created!";
        $this->evilness = $evilness;
        $this->name = $name;
    }

    public function __toString(){
        return (string)$this->name;
    }
}

$bad = new Baddie(3, "bob");

//var_dump($bad);

?>

Here is a screenshot Chrome: http://prntscr.com/bl941w

thanks in advance!

You just created a new object Baddie , but the __toString method is never called. The method only gets called, if you call them directly $bad->__toString() or implicit by an cast ie echo $bad; or $str = (string) $bad

In your case, you cast want to use

$bad = new Baddie(3, "bob");
echo $bad;

You need to call toString()

echo $bad->__toString()

Or just

echo $bad

If echo is called with an object it will search the __toString method and use its result as output.

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