0
0
PHPprogramming~5 mins

Final classes and methods in PHP

Choose your learning style9 modes available
Introduction

Final classes and methods stop other code from changing them. This helps keep your code safe and clear.

When you want to make sure no one changes a class you wrote.
When a method should always work the same way and not be changed.
When you want to protect important parts of your code from mistakes.
When you create a base class that should not be extended.
When you want to keep your code simple and predictable.
Syntax
PHP
final class ClassName {
    final public function methodName() {
        // method code
    }
}

A final class cannot be extended by other classes.

A final method cannot be overridden in child classes.

Examples
This shows a final class Car. You cannot make a new class that extends it.
PHP
<?php
final class Car {
    public function drive() {
        echo "Driving";
    }
}

// This will cause an error:
// class SportsCar extends Car {}
?>
This shows a final method start in class Vehicle. Child classes cannot change this method.
PHP
<?php
class Vehicle {
    final public function start() {
        echo "Starting engine";
    }
}

class Bike extends Vehicle {
    // This will cause an error:
    // public function start() {
    //     echo "Bike starting";
    // }
}
?>
Sample Program

This program creates a final class Book with a final method read. It prints a message when called. Trying to extend the class or override the method will cause errors.

PHP
<?php
final class Book {
    final public function read() {
        echo "Reading book";
    }
}

$myBook = new Book();
$myBook->read();

// Uncommenting below will cause errors:
// class Novel extends Book {}
// class Magazine extends Book {
//     public function read() {
//         echo "Reading magazine";
//     }
// }
?>
OutputSuccess
Important Notes

Use final to protect code you do not want changed.

Final classes cannot be extended at all.

Final methods can be used in non-final classes to protect just that method.

Summary

Final classes stop other classes from extending them.

Final methods stop child classes from changing them.

Use final to keep your code safe and predictable.