OOP With PHP 7: Best Practices & Exception Handling In PHP

Object Oriented Programming OOP PHP
Profile Picture Joton Sutradharβ€’ πŸ“– 3 min read β€’ πŸ“… 12th February 2025

Heads up!

Check my blogs on Dev.to and Medium!

PHP is a versatile scripting language widely used for web development. To build secure and maintainable applications, it is essential to follow best practices, particularly when dealing with object-oriented programming and error handling. This article covers two crucial aspects: using the final keyword to prevent method overriding and handling exceptions effectively with try, catch, and custom exceptions.

1. Using the Final Keyword in PHP to Prevent Overriding

In PHP, the final keyword is used to prevent a class or method from being overridden by subclasses. This is particularly useful when you want to ensure that core logic remains unchanged.

Why Use final?

  • Prevents accidental modifications to critical functionality.

  • Ensures security and stability in framework or library development.

  • Helps maintain intended behavior of a class or method.

Example: Preventing Method Overriding

class BaseClass {
    final public function importantMethod() {
        echo "This method cannot be overridden!";
    }
}

class DerivedClass extends BaseClass {
    // This will cause a fatal error
    /*
    public function importantMethod() {
        echo "Trying to override!";
    }
    */
}

Example: Preventing Class Inheritance

final class SecureClass {
    public function showMessage() {
        echo "This class cannot be extended!";
    }
}

// This will cause a fatal error
/*
class AnotherClass extends SecureClass {
}
*/

Using final ensures that your important methods and classes remain unchanged, avoiding unintentional breakages.

2. Exception Handling in PHP: Try, Catch, and Custom Exceptions

Exception handling in PHP helps manage errors gracefully, improving application reliability. PHP provides the try, catch, and throw mechanisms for handling exceptions.

Basic Exception Handling

try {
    $num = 0;
    if ($num === 0) {
        throw new Exception("Number cannot be zero!");
    }
    echo 100 / $num;
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
}

Using Custom Exceptions

PHP allows defining custom exception classes to handle specific errors.

class CustomException extends Exception {
    public function errorMessage() {
        return "Custom Error: " . $this->getMessage();
    }
}

try {
    $age = 15;
    if ($age < 18) {
        throw new CustomException("Age must be 18 or older.");
    }
    echo "Access granted.";
} catch (CustomException $e) {
    echo $e->errorMessage();
}

Best Practices for Exception Handling

  1. Use Specific Exception Types - Instead of generic Exception, create domain-specific exceptions for clarity.

  2. Log Exceptions - Always log critical errors to track issues.

  3. Avoid Silencing Errors - Ensure meaningful error messages are returned.

  4. Use finally When Necessary - Release resources like database connections or file handlers.

try {
    $file = fopen("test.txt", "r");
    if (!$file) {
        throw new Exception("File not found");
    }
    // Process file
} catch (Exception $e) {
    echo "Error: " . $e->getMessage();
} finally {
    if ($file) {
        fclose($file);
    }
}

By following these best practices, you can create more reliable, maintainable PHP applications.


Subscribe for newsletter for weekly update. Happy coding! πŸš€

Related Blogs
Supercharge Your Laravel App With Queues – A Developer’s Experience With Background Email Sending
Laravel Jobs Queue Queue Jobs Php Joton Sutradhar

As Laravel developers, one of the critical lessons we eventually learn is: not everything should happen in real-time. Whether it's sending emails, processing images, syncing third-party data, or running analytics β€” pushing these resource-heavy or time-consuming tasks to the background is essential for a performant and responsive application.

Profile Picture Joton Sutradhar β€’ πŸ“– 6 min read β€’ πŸ“… 29th May 2025
Mastering The Laravel App Service Pattern
Laravel PHP Service Pattern

As your Laravel application grows, keeping your code organized becomes more important than ever. A bloated controller quickly becomes hard to read, test, and maintain. One of the best solutions to this problem is using the Service Pattern β€” a pattern that helps separate your business logic from your controllers.

Profile Picture Joton Sutradhar β€’ πŸ“– 6 min read β€’ πŸ“… 27th May 2025
OOP With PHP 6: Namespaces And Dependency Injection
Object Oriented Programming OOP PHP

Managing large codebases efficiently is a crucial aspect of PHP development. Two key concepts that help in this regard are Namespaces and Dependency Injection.

Profile Picture Joton Sutradhar β€’ πŸ“– 3 min read β€’ πŸ“… 10th February 2025
Subscribe to my newsletter

Get recent projects & blog updates to your inbox.

I never share your email. Read our privacy policy.

© 2025 Joton Sutradhar. All rights reserved.