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

Final Keyword ใน PHP


Final keyword ใช้ใน PHP สำหรับ methods และ classes Final สำหรับ methods ป้องกัน method overriding ส่วน final สำหรับ classes ป้องกัน Inheritance

ตัวอย่าง

การทำงานกับ final keyword ใน PHP โค้ดมีดังนี้ ที่นี่เรามี final method −

<?php 
    class Base { 
        final function display() { 
            echo "Base class function declared final!"; 
        } 
        function demo() { 
            echo "Base class function!"; 
        } 
    } 
    class Derived extends Base { 
        function demo() { 
            echo "Derived class function!"; 
        } 
    } 
    $ob = new Derived; 
    $ob->demo(); 
?>

ผลลัพธ์

จะผลลัพธ์ดังนี้ −

Derived class function!

ตัวอย่าง

มาดูตัวอย่างที่มี final class −

<?php 
    final class Base { 
        final function display() { 
            echo "Base class function declared final!"; 
        } 
        function demo() { 
            echo "Base class function!"; 
        } 
    } 
    class Derived extends Base { 
        function demo() { 
            echo "Derived class function!"; 
        } 
    } 
    $ob = new Derived; 
    $ob->demo(); 
?>

ผลลัพธ์

จะผลลัพธ์ดังนี้ คือ error เนื่องจากเราพยายามสร้าง derived class จาก final base class −

PHP Fatal error: Class Derived may not inherit from final class (Base) in /home/cg/root/6985034/main.php on line 19