0
0
PHPprogramming~5 mins

__toString for string representation in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
AA string representation of the object
BAn integer value
CA boolean value
DNothing, it is void
What happens if you echo an object without a __toString method?
APHP prints nothing
BPHP prints 'Object'
CPHP prints 'Array'
DPHP throws a fatal error
Which of these is the correct signature for __toString?
Apublic function __toString(): string
Bpublic function __toString(string $param): string
Cprivate function __toString()
Dpublic function __toString(): void
Can __toString be used to customize what is shown when an object is echoed?
AOnly if the object implements an interface
BYes
CNo
DOnly in PHP 8+
Which keyword is used to define the __toString method?
Adef
Bmethod
Cfunction
Dproc
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.