What is final class php

When to use Final in PHP?

I know what the definition is of a Final class, but I want to know how and when final is really needed.

If I understand it correctly, ‘final’ enables it to extend ‘Foo’. Can anyone explain when and why ‘final’ should be used? In other words, is there any reason why a class should not be extended? If for example class ‘Bar’ and class ‘Foo’ are missing some functionality, it would be nice to create a class which extends ‘Bar’.

5 Answers 5

There is a nice article about «When to declare classes final». A few quotes from it:

TL;DR: Make your classes always final , if they implement an interface, and no other public methods are defined

Why do I have to use final ?

  1. Preventing massive inheritance chain of doom
  2. Encouraging composition
  3. Force the developer to think about user public API
  4. Force the developer to shrink an object’s public API
  5. A final class can always be made extensible
  6. extends breaks encapsulation
  7. You don’t need that flexibility
  8. You are free to change the code

When to avoid final :

  1. There is an abstraction (interface) that the final class implements
  2. All of the public API of the final class is part of that interface

P.S. Thanks to @ocramius for great reading!

For general usage, I would recommend against making a class final . There might be some use cases where it makes sense: if you design a complex API / framework and want to make sure that users of your framework can override only the parts of the functionality that you want them to control it might make sense for you to restrict this possibility and make certain base classes final .

Читайте также:  Расширенный вывод ошибок settings php битрикс

e.g. if you have an Integer class, it might make sense to make that final in order to keep users of your framework form overriding, say, the add(. ) method in your class.

It has often surprised me in the past just how often I have needed to do ridiculous things which were blocked casually, like your Integer class example. Granted, each time it’s happened it has been the product of weeks of careful research of the code, but it has happened already a few times.

-1: This is pure opinion (so makes it generally a bad answer as this would be a reason to close-vote the question instead); but next to that, most likely not a thoughful one in the sense of programming. See programmers.stackexchange.com/q/89073/24482

@hakre I see it backwards, the question is the one that (as it is currently stated) encourages opinion based answers, there is a flag for this

  1. Declaring a class as final prevents it from being subclassed—period; it’s the end of the line.
  2. Declaring every method in a class as final allows the creation of subclasses, which have access to the parent class’s methods, but cannot override them. The subclasses can define additional methods of their own.
  3. The final keyword controls only the ability to override and should not be confused with the private visibility modifier. A private method cannot be accessed by any other class; a final one can.

—— quoted from page 68 of the book PHP Object-Oriented Solutions by David Powers.

final childClassname extends ParentsClassname < // class definition omitted >

This covers the whole class, including all its methods and properties. Any attempt to create a child class from childClassname would now result in a fatal error. But,if you need to allow the class to be subclassed but prevent a particular method from being overridden, the final keyword goes in front of the method definition.

class childClassname extends parentClassname < protected $numPages; public function __construct($autor, $pages) < $this->_autor = $autor; $this->numPages = $pages; > final public function PageCount() < return $this->numPages; > > 

In this example, none of them will be able to overridden the PageCount() method.

You would use it where the class contained methods which you specifically do not want overridden. This may be because doing do would break your application in some way.

Sorry I got carried away with the submit button. Edited. Please let me know if you would like me to expand

You would use it where the class contained methods which you specifically do not want overridden. This may be because doing do would break your application in some way. could you give an example? Instead of overriding, extending could also add functionality instead of overriding, or??

@Gumbo, I just want to know if creating Final classes is a bad practice and the PHP manual ain’t telling me that. Can you tell me where I can find that?

My 2 cents:

When To Use final :

Why?

  • it breaks the ability to use test doubles when unit testing
  • could lead to increased code duplication because of gaps in functionality in downstream code
  • the reasons to use it are all training issues being addressed with a radical shortcut

Bad Reasons to Use It:

  • Preventing massive inheritance chain of doom (training issue)
  • Encouraging composition (training issue)
  • Force the developer to think about user public API (training issue)
  • Force the developer to shrink an object’s public API (training issue? code reviews?)
  • A final class can always be made extensible (relevance?)
  • extends breaks encapsulation (what? poor encapsulation breaks encapsulation; not inheritance. inheritance is not inherently evil.)
  • You don’t need that flexibility (typical thinking behind short-sighted development. be prepared to hit a feature wall + training issue)
  • You are free to change the code (relevance?)

With respect, I disagree vehemently with this. First off, it’s not a «training issue» — sometimes the people using your class simply aren’t your responsibility, such as if you’re writing a library, but you still want to stop them shooting themselves in the foot with inheritance. The mock issue can be overcome by having the class implement an interface and mocking that. If some of the functionality needs to be reused it can be extracted to a subclass or trait, and if you need to duplicate a significant amount of code to reimplement functionality the class was probably too big anyway.

«training issue» means it’s really not a coding problem, it’s a people problem. talk to the people. document better. have frequent design discussions.

Completely agree with this answer. I’m tired of seeing the final keyword on every class in a php project. Seems some devs are even proud of saying that in their IDE they have the final keyword in their class template file. This is horrible. C++ also received the final keyword and you have videos already talking about how you should be extremely careful when using it.

So, this is an old thread now. In addition to all other points made above, the Final keyword is just fundamentally too much hubris for me to adopt. I cannot assume that any 1 approach to a software problem is the only and best approach ever. This is a journey of perpetual learning. Therefore, whenever I write code, I want to make life easier, not harder for the next designer to do whatever they want/need to extend & test functionality for their project. I won’t be using Final unless I’m on a client’s project where I have direct orders to do so. I said what I said.

Источник

What is final class php

Reg.ru: домены и хостинг

Крупнейший регистратор и хостинг-провайдер в России.

Более 2 миллионов доменных имен на обслуживании.

Продвижение, почта для домена, решения для бизнеса.

Более 700 тыс. клиентов по всему миру уже сделали свой выбор.

Бесплатный Курс «Практика HTML5 и CSS3»

Освойте бесплатно пошаговый видеокурс

по основам адаптивной верстки

на HTML5 и CSS3 с полного нуля.

Фреймворк Bootstrap: быстрая адаптивная вёрстка

Пошаговый видеокурс по основам адаптивной верстки в фреймворке Bootstrap.

Научитесь верстать просто, быстро и качественно, используя мощный и практичный инструмент.

Верстайте на заказ и получайте деньги.

Что нужно знать для создания PHP-сайтов?

Ответ здесь. Только самое важное и полезное для начинающего веб-разработчика.

Узнайте, как создавать качественные сайты на PHP всего за 2 часа и 27 минут!

Создайте свой сайт за 3 часа и 30 минут.

После просмотра данного видеокурса у Вас на компьютере будет готовый к использованию сайт, который Вы сделали сами.

Вам останется лишь наполнить его нужной информацией и изменить дизайн (по желанию).

Изучите основы HTML и CSS менее чем за 4 часа.

После просмотра данного видеокурса Вы перестанете с ужасом смотреть на HTML-код и будете понимать, как он работает.

Вы сможете создать свои первые HTML-страницы и придать им нужный вид с помощью CSS.

Бесплатный курс «Сайт на WordPress»

Хотите освоить CMS WordPress?

Получите уроки по дизайну и верстке сайта на WordPress.

Научитесь работать с темами и нарезать макет.

Бесплатный видеокурс по рисованию дизайна сайта, его верстке и установке на CMS WordPress!

Хотите изучить JavaScript, но не знаете, как подступиться?

После прохождения видеокурса Вы освоите базовые моменты работы с JavaScript.

Развеются мифы о сложности работы с этим языком, и Вы будете готовы изучать JavaScript на более серьезном уровне.

*Наведите курсор мыши для приостановки прокрутки.

Ключевое слово final (завершенные классы и методы в PHP)

Наследование открывает большие возможности для широкого поля действий в пределах иерархии класса.

Вы можете переопределить класс или метод, чтобы вызов в клиентском методе приводил к совершенно разным результатам, в зависимости от типа объекта, переданного методу в качестве аргумента.

Но иногда код класса или метода необходимо «зафиксировать», если предполагается, что в дальнейшем он не должен изменяться.

Если вы создали необходимый уровень функциональности для класса и считаете, что его переопределение может только повредить отлаженной работе приложения, воспользуйтесь ключевым словом final.

Ключевое слово final позволяет положить конец наследованию. Для завершенного класса нельзя создать подкласс, а завершенный метод нельзя переопределить.

Давайте объявим класс завершенным:

Теперь давайте попробуем создать подкласс класса Checkout.

class IllegalCheckout extends Checkout < // тело класса >

Выполнение данного кода приведет к ошибке.

PHP Fatal error: class IllegalCheckout may not inherit from final class (Checkout) in .

По-русски это звучало бы примерно так: Класс IllegalCheckout не может быть унаследован от завершенного класса Checkout.

Мы можем несколько «смягчить» ситуацию, объявив завершенным только метод в классе Checkout, а не весь класс. Кстати, ключевое слово final должно стоять перед любыми другими модификаторами, такими как, например, protected или static.

Итак, объявляем завершенный метод:

Теперь мы можем создать подкласс класса Checkout, однако любая попытка переопределить метод totalize() приведет к неустранимой ошибке.

class IllegalCheckout extends Checkout < final function totalize() < // тело функции >>

Выполнение кода, приведенного выше, даст нам такую ошибку:

// Fatal error: cannot override final method // Checkout::totalize() in .

Что в переводе на великий могучий означает: Нельзя переопределить завершенный метод сheckout::totalize().

В хорошем объектно-ориентированном коде во главу угла обычно ставится строго определенный интерфейс. Но за этим интерфейсом могут скрываться разные реализации. Разные классы или сочетания классов могут соответствовать общим интерфейсам, но при этом вести себя по-разному в разных ситуациях.

Объявляя класс или метод завершенным, мы тем самым ограничиваем его гибкость. В некоторых случаях это выгодно, и мы рассмотрим такие ситуации в других статьях позже на конкретных примерах.

Однако, прежде чем объявлять что-либо завершенным, следует хорошенько подумать: действительно ли нет таких ситуаций, в которых переопределение было бы полезным?

Конечно, мы можем передумать, но внести изменения впоследствии может быть нелегко, например, если вы распространяете библиотеку для совместного использования.

Отсюда простой вывод: будьте осторожны и четко осознавайте свои действия, если используете ключевое слово final.

Понравился материал и хотите отблагодарить?
Просто поделитесь с друзьями и коллегами!

Смотрите также:

Источник

Оцените статью