How can delayed database connections be effectively managed within a custom database class in PHP?

Delayed database connections can be effectively managed within a custom database class in PHP by implementing a lazy loading technique. This means that the database connection is only established when it is actually needed, rather than at the moment the class is instantiated. By doing so, resources are conserved and unnecessary connections are avoided.

class CustomDatabase {
    private $connection;

    public function getConnection() {
        if ($this->connection === null) {
            $this->connection = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
        }
        return $this->connection;
    }

    // Other database methods can use $this->getConnection() to get the connection
}