Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> PHP

Stringable Interface ใน PHP 8 คืออะไร

ใน PHP 8 มี Stringable Interface ใหม่ (__toSting) เพิ่มเข้ามา เมธอดนี้เริ่มต้นด้วย underscore คู่ (__ ) เมธอด __toString อนุญาตให้รับการแทนค่าของอ็อบเจกต์เป็นสตริง เมื่อคลาสกำหนดเมธอดโดยใช้ __toString จะถูกเรียกเมื่ออ็อบเจกต์ต้องถูกจัดการเป็นสตริง

ตัวอย่าง: Stringable Interface ใช้ __toString

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

ผลลัพธ์

Employee Name

ใน PHP 8 Stringable interface ทำให้การส่งผ่านสตริงง่ายขึ้น Stringable interface จะถูกเพิ่มโดยอัตโนมัติเมื่อคลาส implement เมธอด __toString ไม่จำเป็นต้อง implement interface อย่างชัดเจน Stringable interface อาจช่วยในการ type hinting เมื่อมีการบังคับ strict types (string_types=1)

ตัวอย่าง: ใช้ Stringable Interface ใน PHP 8

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

ผลลัพธ์

bool(true)