Skip to Content
Mastering PHP 7
book

Mastering PHP 7

by Branko Ajzele
June 2017
Intermediate to advanced
536 pages
9h 49m
English
Packt Publishing
Content preview from Mastering PHP 7

Using __toString()

The __toString() magic method triggers when we use an object in a string context. It allows us to decide how the object will react when it is treated like a string.

Let's take a look at the following example:

<?phpclass User{  protected $name;  protected $age;  public function __construct($name, $age)  {    $this->name = $name;    $this->age = $age;  }}$user = new User('John', 34);echo $user;

Here, we have a simple User class that accepts the $name and $age parameters through its constructor method. Other than that, there is nothing else to indicate how the class should respond to the attempt of using it in the string context, which is exactly what we are doing right after the class declaration, as we are trying to echo the object ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Learning PHP 7

Learning PHP 7

Antonio L Zapata (GBP)
Upgrading to PHP 5

Upgrading to PHP 5

Adam Trachtenberg

Publisher Resources

ISBN: 9781785882814Supplemental Content