Recall & Review
beginner
What is the purpose of the
__toString method in PHP?The <code>__toString</code> method allows a class to define how its objects are converted to a string, for example when echoing the object.Click to reveal answer
beginner
How do you declare the
__toString method in a PHP class?You declare it as a public method named <code>__toString</code> that returns a string. Example:<br><pre>public function __toString(): string { return 'text'; }</pre>Click to reveal answer
beginner
What happens if you try to echo an object without a
__toString method?PHP will throw a fatal error because it does not know how to convert the object to a string.
Click to reveal answer
intermediate
Can the
__toString method accept parameters?No, the
__toString method cannot accept any parameters. It must be declared without arguments.Click to reveal answer
beginner
Give a simple example of a PHP class with a <code>__toString</code> method.Example:<br><pre>class Person {
private string $name;
public function __construct(string $name) {
$this->name = $name;
}
public function __toString(): string {
return "Person: " . $this->name;
}
}
$person = new Person('Anna');
echo $person; // Outputs: Person: Anna</pre>Click to reveal answer
What does the
__toString method in PHP return?✗ Incorrect
The
__toString method must return a string that represents the object.What happens if you echo an object without a
__toString method?✗ Incorrect
PHP cannot convert the object to a string without
__toString and throws a fatal error.Which of these is the correct signature for
__toString?✗ Incorrect
__toString must be public, take no parameters, and return a string.Can
__toString be used to customize what is shown when an object is echoed?✗ Incorrect
The main use of
__toString is to customize the string shown when echoing an object.Which keyword is used to define the
__toString method?✗ Incorrect
In PHP, methods are defined using the
function keyword.Explain what the
__toString method does in PHP and why it is useful.Think about how objects behave when printed.
You got /3 concepts.
Write a simple PHP class with a
__toString method that returns a custom message.Remember the method signature and return type.
You got /4 concepts.