static class that inheritance of nonstatic class. nonstatic class is connection to database class in php

To create a static class that inherits from a nonstatic class in PHP, you can use the extends keyword to specify the parent class. However, if the nonstatic class is a database connection class, it is generally not a good idea to make it static, as connection objects often need to be specific to the context in which they are used.

That said, here's an example of how to create a static class that inherits from a nonstatic class:

main.php
class Database {
    private $host;
    private $username;
    private $password;
    private $database;

    public function __construct($host, $username, $password, $database) {
        $this->host = $host;
        $this->username = $username;
        $this->password = $password;
        $this->database = $database;
        // create database connection
    }

    public function query($sql) {
        // execute SQL query and return results
    }
}

class StaticDatabase extends Database {
    public static function query($sql) {
        $db = new Database('localhost', 'user', 'pass', 'db');
        // create and execute query using nonstatic database connection
        return $db->query($sql);
    }
}
713 chars
27 lines

In this example, StaticDatabase extends Database, but overrides the query method to use a new instance of Database each time it is called. Rather than using a static database connection, which can cause problems with concurrent requests, this approach creates a new connection object for each query.

gistlibby LogSnag