- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is Stringable Interface in PHP 8?
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
<?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
<?php declare(strict_types=1); class Employee { public function __toString() { return 'Employee Details'; } } $emp = new Employee; var_dump($emp instanceof Stringable); ?>
Output
bool(true)
Advertisements