__toString

The __toString() method allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.

Converting objects to strings

The magic method __tostring() is called, if available o

Includes print, string interpolation, operation with strings, calling functions that expect strings, …

Example

<?php
 class TestClass{
 public $foo;
 public function __construct($foo){
 $this->foo = $foo;
 }

public function __toString(){
 return $this->foo;
 }
 }
 $class = new TestClass('Hello');
 echo $class;
?>

Leave a Reply

Your email address will not be published. Required fields are marked *