PHP OOP v3 Final Keyword

PHP concept

Why do we use the final keyword?

When writing code with OOP in PHP, we constantly use inheritance. However, sometimes we may want to prevent a class from being inherited by other classes. For this, PHP offers us the final keyword.

In my previous article, I explained the concept of PHP OOP inheritance, if you haven’t read it:
https://duzzii.com/php-oop-v2-inheritance/.

<?php

final class Example{

    public function printContent(){
        return "Php OOP Final Keyword";
    }
}

class SecondExample extends Example { 
    public function printContent(){
        return "Php OOP Final Keyword";
    }
}
// Error:  Class SecondExample may not inherit from final class (Example)

?>

In addition, the final keyword can be used for functions.

Advertisements

The method in which we use the keyword Final in php cannot be rewritten in another class.

<?php

class FunctionExample{

    final public function printContent(){
        return "Php OOP Final Keyword (Function)";
    }
}

class SecondFunctionExample extends FunctionExample {

    public function printContent(){
        return "Php OOP Final Keyword";
    }
}

// Error: 'SecondFunctionExample::printContent()' cannot override final method

?>

We cannot declare properties as final,
we can only declare classes and methods as final.
For more information.
You can follow php.net for updates and more about PHP OOP.
https://www.php.net/manual/en/language.oop5.php

Please report the parts you see incorrect or incomplete. And don’t forget to subscribe to our newsletter for more articles. Healthy days!

Liked it? Take a second to support Selim on Patreon!
Advertisements

Selim

Backend Developer, Öğrenci, Blogger

You may also like...

Yorum yap

%d blogcu bunu beğendi: