Skip to content
PHP Logo

What are the best practices for making instances of handler classes accessible to all other classes in a PHP project?

To make instances of handler classes accessible to all other classes in a PHP project, one common approach is to use a design pattern like the Singleton pattern. This ensures that only one instance of the handler class is created and provides a global point of access to it. By using a static method to retrieve the instance, other classes can easily access the handler class without needing to create new instances.

php
class Handler {
    private static $instance;

    private function __construct() {
        // private constructor to prevent instantiation
    }

    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new Handler();
        }
        return self::$instance;
    }

    public function handleRequest($request) {
        // handle request logic
    }
}

// Accessing the handler instance from other classes
$handler = Handler::getInstance();
$handler->handleRequest($request);