0
0
PHPprogramming~15 mins

__toString for string representation in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
__toString for string representation
📖 Scenario: You are creating a simple PHP class to represent a book in a library. You want to show the book's title and author as a string whenever the book object is printed.
🎯 Goal: Build a PHP class called Book with properties for title and author. Implement the __toString() method to return a string showing the book's title and author in the format: "Title by Author".
📋 What You'll Learn
Create a class named Book with two public properties: title and author.
Add a constructor to set the title and author when creating a new Book object.
Implement the __toString() method to return the string "Title by Author" using the object's properties.
Create an instance of Book with title "1984" and author "George Orwell".
Print the Book object to display the string representation.
💡 Why This Matters
🌍 Real World
Classes with <code>__toString()</code> help display objects in a readable way, useful in logging, debugging, or showing information to users.
💼 Career
Understanding <code>__toString()</code> is important for PHP developers to create clean, maintainable code that interacts well with strings and output.
Progress0 / 4 steps
1
Create the Book class with properties
Create a PHP class called Book with two public properties: title and author.
PHP
Need a hint?

Use class Book { public string $title; public string $author; } to define the class and properties.

2
Add a constructor to set title and author
Add a constructor method __construct to the Book class that takes two parameters: $title and $author, and sets the class properties accordingly.
PHP
Need a hint?

Define public function __construct(string $title, string $author) and assign the parameters to $this->title and $this->author.

3
Implement the __toString() method
Inside the Book class, add a public method __toString() that returns a string in the format "Title by Author" using the object's title and author properties.
PHP
Need a hint?

Use public function __toString(): string { return "$this->title by $this->author"; } inside the class.

4
Create a Book object and print it
Create a new Book object called $book with title "1984" and author "George Orwell". Then print the $book object.
PHP
Need a hint?

Create the object with new Book("1984", "George Orwell") and print it with print($book);.