Search code examples
phpclassobjectoopconstructor

I want to show all the data inside calling object in PHP, but it show me the fatal error that Object of class Book could not be converted to string


I created a class of Book inside index.php where i create some variables and also a constructor that takes the values from the objects when i put my values inside Object it show me the fatal error that Object of class Book could not be converted to strings , What's the problem with that code. I also attached my code.

My code inside index.php file

<?php
    class Book{
        var $title;
        var $author;
        var $pages;
        var $price;
        function __construct($a_title , $a_author , $a_pages , $a_price){
            $this->title=$a_title;
            $this->author=$a_author;
            $this->pages=$a_pages;
            $this->price=$a_price;

        }
    }
    $book1 = new Book("One Day The Life will be End","Muhammad Mujtaba",400,32500);
    $book2 = new Book("A Horse Man In The Sky","Ali Hassan",550,2000);
    echo $book1;
    echo "<br> <br>";
    echo $book2;
?>

I want to show all values which I will put inside my objects can be see on the browser but it's show me the fatal error.


Solution

  • I think unless you create a __toString() method in your class, you won't let PHP convert your objects from this class into a string, which is implicitly what you're doing when you try to echo such an object.

    So, as I mentioned above you can

    • create a __toString() method if really you want to be able to "echo" your objects (see the doc on magic methods)
    • use the var_dump($book1) or print_r($book1) functions, but it will give very raw output.