What is Stringable Interface in PHP 8?

PHPServer Side ProgrammingProgramming

In PHP 8, a new Stringable Interface (__toSting) is added. This method starts with the double underscore (__). The __toString method allows getting an object represented as a string. When a class defines a method using __toString, then it will call an object whenever it needs to treat as a string.

Example: Stringable Interface using __toString

 Live Demo

<?php
   class Employee{
      public function __toString(): string
      {
         return 'Employee Name';
      }
   }
   $employee = new Employee();
   print_r((string)$employee);
?>

Output

Employee Name

In PHP 8, the Stringable interface makes it easy to pass strings. A Stringable interface adds automatically once a class implements the __toString method. It does not require implementing the interface explicitly. The Stringable interface can be helpful for type hinting whenever strict types are imposed (string_types=1).

Example: Using Stringable Interface in PHP 8

 Live Demo

<?php
   declare(strict_types=1);
   class Employee {
      public function __toString() {
         return 'Employee Details';
      }
   }
   $emp = new Employee;
   var_dump($emp instanceof Stringable);
?>

Output

bool(true)
raja
Published on 01-Apr-2021 06:33:50
Advertisements