How can class constants and global variables be used effectively in PHP to manage database connections across different classes?

To manage database connections across different classes in PHP, class constants can be used to store database connection information such as host, username, password, and database name. Global variables can be utilized to store the actual database connection object. By defining these constants and variables in a central location, such as a separate config file, they can be easily accessed and reused throughout the application without the need to repeatedly define connection parameters in each class.

// config.php
class DatabaseConfig {
    const HOST = 'localhost';
    const USERNAME = 'root';
    const PASSWORD = 'password';
    const DATABASE = 'my_database';
}

// database.php
class Database {
    private static $connection;

    public static function getConnection() {
        if (!self::$connection) {
            self::$connection = new mysqli(DatabaseConfig::HOST, DatabaseConfig::USERNAME, DatabaseConfig::PASSWORD, DatabaseConfig::DATABASE);
        }
        return self::$connection;
    }
}

// example-usage.php
require_once 'config.php';
require_once 'database.php';

$connection = Database::getConnection();
// Use $connection to interact with the database