Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A final class in PHP is a class declaration prefixed with the final keyword, which explicitly prevents the class from being inherited or extended by any other class. When a class is marked as final, it terminates the inheritance chain, ensuring its internal implementation and state cannot be modified or overridden through subclassing.
final class ClassName {
    // Properties and methods
}

Engine Behavior and Inheritance

If a script attempts to define a class that inherits from a final class using the extends keyword, the PHP engine will halt execution and throw a Fatal error at compile time.
final class ParentClass {
    public function execute(): void {}
}

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

Method Redundancy

Because a final class cannot be subclassed, it is impossible for any of its methods to be overridden. While PHP allows you to declare individual methods as final within a final class, doing so is logically redundant and has no additional effect on the engine’s behavior.

Instantiation and Composition

The final modifier strictly governs inheritance; it does not affect instantiation or composition. A final class retains standard object-oriented capabilities:
  • It can be instantiated using the new keyword.
  • It can inherit from another (non-final) class.
  • It can implement one or more interfaces.
  • It can import traits.
class BaseEntity {}
interface CustomSerializable {}
trait Timestampable {}

// Valid: A final class extending a base class, implementing an interface, and using a trait
final class User extends BaseEntity implements CustomSerializable {
    use Timestampable;
    
    public string $username;
}

$user = new User(); // Valid instantiation

Structural Restrictions

  • Abstract Modifier: A class cannot be declared as both abstract and final simultaneously. These modifiers are mutually exclusive. Attempting to combine them (abstract final class) will result in a Fatal error: Cannot use the final modifier on an abstract class.
  • Interfaces and Traits: The final keyword cannot be applied to interface or trait declarations. The PHP engine will throw a parse error, as the fundamental architecture of interfaces and traits requires them to be implemented or consumed by other structures.
  • Readonly Classes: As of PHP 8.2, the final keyword can be combined with the readonly modifier (final readonly class Name {}).
Master PHP with Deep Grasping Methodology!Learn More