I would like to know will the object which created from a class with FINAL use less memory? Or FINAL is just a "config" for the class?
Asked
Active
Viewed 67 times
0
-
https://www.php.net/manual/en/language.oop5.final.php – k0pernikus Aug 04 '21 at 07:47
-
1There's no inherent reason why a `final` class would use less memory. It *may* or may not use less memory for some internal optimisation reason in specific PHP versions, but because it's just an internal optimisation, that may or may not be the case in the next PHP version. The manual doesn't mention anything or guarantee anything in this regard, so just assume that memory use has zero to do with it. – deceze Aug 04 '21 at 07:50
-
1`final` implies the interpreter needs to perform additional checks, so I wouldn't be surprised to find a small increase in memory usage. But, as said, it belongs to PHP internals and it's probably nothing worth taking into account. – Álvaro González Aug 04 '21 at 07:57
-
1@Álvaro I would expect the compiler to have to perform that check anyway for any extending class, along the lines of `for c in chain_of_parents(cls): if c.final: throw new Exception`. In that case, `final` is just an attribute and doesn't incur any additional processing nor memory. That's just my guess though, haven't looked at the actual implementation. – deceze Aug 04 '21 at 08:02
1 Answers
2
The final keyword's purpose is basically to prevent a class from being extended. Memory should not be a concern.
The final keyword prevents child classes from overriding a method by prefixing the definition with final. If the class itself is being defined final then it cannot be extended.
Biggest downside that this also applies when trying to mock such a class in unit tests.
If you want to mock such a class you have to use certain libraries to remove the final keyword on-the-fly. (E.g.: dg/bypass-finals). It may make sense in certain projects, though I barely see it as useful. Rather than relying on the final
keyword for classes, I don't extend certain classes by convention.

k0pernikus
- 60,309
- 67
- 216
- 347