W3docs

final

The "final" keyword is a feature of object-oriented programming in PHP that allows a method, class or property to be marked as final, preventing it from being

The PHP "final" Keyword: A Comprehensive Guide

The "final" keyword is a feature of object-oriented programming in PHP that allows a method, class or property to be marked as final, preventing it from being overridden or extended by child classes. In this article, we will explore the syntax and usage of the "final" keyword in depth, and provide plenty of examples to help you master this important PHP feature.

Syntax

The "final" keyword is used to mark a method, class or property as final. Here is the basic syntax for using the "final" keyword in PHP:

The PHP syntax of final

final class MyClass {
  // code to be executed
}

class MyChildClass extends MyClass {
  // Fatal error: Class MyChildClass may not inherit from final class (MyClass)
}

In this example, the "final" keyword is used to mark a class as final, preventing it from being extended by child classes.

Examples

Let's look at some practical examples of how the "final" keyword can be used:

Examples of PHP final

<?php

// Example 1
class Fruit
{
  final public function getInfo()
  {
    echo "This is a fruit.";
  }
}

class Apple extends Fruit
{
  // Fatal error: Cannot override final method Fruit::getInfo()
}

// Example 2
class Car
{
  final public $model = "Toyota"; // Requires PHP 8.1+
}

class Toyota extends Car
{
  // Fatal error: Cannot override final property Car::$model
}

In these examples, we use the "final" keyword to mark a method or property as final, preventing it from being overridden or extended by child classes.

Benefits

Using the "final" keyword has several benefits, including:

  • Enforced design constraints: The "final" keyword prevents unintended overrides, ensuring consistent behavior across subclasses.
  • Predictable behavior: It guarantees that critical methods or properties cannot be altered by child classes, maintaining the intended class contract.

Conclusion

In conclusion, the "final" keyword is a powerful tool for PHP developers who are using object-oriented programming. It allows you to mark a method, class or property as final, preventing it from being overridden or extended by child classes, which enforces design constraints and ensures predictable behavior. We hope this comprehensive guide has been helpful, and we wish you the best of luck as you continue to develop your PHP skills.

Practice

Practice

What does the 'final' keyword denote in PHP?