Table of Contents
Final Classes
Final Methods
When to Use Final
Home Backend Development PHP Tutorial How to use final classes and methods in PHP?

How to use final classes and methods in PHP?

Sep 28, 2025 am 05:55 AM
php final class

Final classes and methods in PHP prevent inheritance and overriding to protect critical code. 2. A final class cannot be extended, ensuring its behavior remains unchanged. 3. A final method cannot be overridden, preserving consistent implementation across subclasses. 4. Use final for security-sensitive or core logic requiring integrity, but avoid overuse to maintain flexibility.

How to use final classes and methods in PHP?

A final class or method in PHP is a way to prevent inheritance or method overriding. This feature helps maintain the integrity of critical code by stopping unintended modifications in child classes.

Final Classes

When you declare a class as final, it cannot be extended. Any attempt to inherit from it will result in a fatal error.

Use a final class when you want to ensure that no other class alters its behavior through inheritance.

Example:

final class DatabaseConnection {<br>    public function connect() {<br>        return "Connected to the database";<br>    }<br>}<br><br>// This will cause a fatal error:<br>// class MySQLConnection extends DatabaseConnection { } // Error!

Final Methods

A final method inside a class cannot be overridden in a child class. The method remains available through inheritance, but its implementation is locked.

This is useful when certain behaviors must remain consistent across all subclasses.

Example:

class Logger {<br>    public function log($message) {<br>        echo "Logging: " . $message;<br>    }<br><br>    final public function getLogTime() {<br>        return date('Y-m-d H:i:s');<br>    }<br>}<br><br>class FileLogger extends Logger {<br>    // This is fine:<br>    public function log($message) {<br>        file_put_contents('log.txt', $message, FILE_APPEND);<br>    }<br><br>    // This would cause an error:<br>    // public function getLogTime() { } // Not allowed!<br>}

When to Use Final

Apply final when:

  • You have security-sensitive logic that must not be altered.
  • The class or method relies on internal consistency that could break if changed.
  • You're building a library and want to protect core functionality.

Don’t overuse it. Only make classes or methods final when there's a clear reason. Overusing final can reduce flexibility for legitimate use cases.

Basically, final keeps your code predictable and secure where needed. It’s a simple keyword with strong implications—use it wisely.

The above is the detailed content of How to use final classes and methods in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

How to implement a singleton pattern in PHP? How to implement a singleton pattern in PHP? Sep 25, 2025 am 12:27 AM

Singleton pattern ensures that a class has only one instance and provides a global access point for scenarios where a single object coordinates the operation of the system, such as database connections or configuration management. 2. Its basic structure includes: private static attribute storage instances, private constructors prevent external creation, private cloning methods prevent copying, and public static methods (such as getInstance()) for obtaining instances. 3. Get a unique instance in PHP by calling getInstance() method, and returns the same object reference no matter how many times it is called. 4. Under the standard PHP request model, thread safety is not necessary to be considered, but synchronization issues need to be paid attention to in long run or multi-threaded environments, and PHP itself does not support native lock mechanism. 5. Although singletons are useful,

How to use the null coalescing operator (??) in PHP? How to use the null coalescing operator (??) in PHP? Sep 25, 2025 am 01:28 AM

Answer: PHP's empty merge operator (??) is used to check whether a variable or array key exists and is not null. If it is true, it returns its value, otherwise it returns the default value. It avoids the use of lengthy isset() checks, is suitable for handling undefined variables and array keys, such as $username=$userInput??'guest', and supports chain calls, such as $theme=$userTheme??$defaultTheme??'dark', which is especially suitable for form, configuration, and user input processing, but only excludes null values, empty strings, 0 or false are considered valid values ​​to return.

How to implement an interface in a PHP class? How to implement an interface in a PHP class? Sep 25, 2025 am 05:34 AM

Use the implements keyword to implement the interface, and the class must provide specific implementations of all methods in the interface. 2. Define the interface to declare the method using the interface keyword. 3. Class implements interface and overrides methods. 4. Create an object and call the method to output the result. 5. A class can implement multiple interfaces to ensure code specification and maintainability.

How to sanitize user input to prevent XSS in PHP? How to sanitize user input to prevent XSS in PHP? Sep 25, 2025 am 05:19 AM

TopreventXSSinPHP,sanitizeuserinputandescapeoutputbasedoncontextusinghtmlspecialchars()forHTML,json_encode()forJavaScript,andvalidatestrictlywithfilter_var()forexpecteddatatypes,whileavoidingdeprecatedfunctionsandusingContent-Security-Policyheadersfo

How to use GET and POST methods in an HTML form with PHP? How to use GET and POST methods in an HTML form with PHP? Sep 25, 2025 am 03:46 AM

The GET method attaches data to the URL, which is suitable for non-sensitive information; the POST method sends data through the request body, which is more secure and suitable for sensitive information.

MBTI free test website entrance_ MBTI personality test free link address MBTI free test website entrance_ MBTI personality test free link address Sep 24, 2025 pm 05:00 PM

The entrance to the MBTI free test website is https://www.16personalities.com/ch. The platform provides a Chinese interface. Users can anonymously conduct tests containing basic and complete versions. They complete multiple-choice questions about 72 questions in about 15 to 20 minutes. The system instantly generates a personalized report covering personality type code, personality analysis and career social suggestions, and supports PDF export, and data encryption and processing without retention.

How to find the intersection of two arrays in PHP? How to find the intersection of two arrays in PHP? Sep 26, 2025 am 06:23 AM

Use the array_intersect() function to find the intersection of two arrays, which returns elements that exist in each array at the same time, and the key names are retained from the first array. For example: $arr1=['apple','banana','orange'];$arr2=['banana','kiwi','apple']; The result is ['apple','banana'].

How to set a default timezone in PHP? How to set a default timezone in PHP? Sep 26, 2025 am 06:22 AM

SetthedefaulttimezoneinPHPusingdate_default_timezone_set('America/New_York');withavalididentifierlikeUTCorEurope/Londontoensureconsistentdate/timehandlingacrossfunctionsandenvironments.

See all articles