简体   繁体   中英

Inheriting database connection in PHP OOP

My abstract class Database is made for database interaction and any child of this class (UserDatabase, ActionDatabase, EventDatabase) inherits its database connection which is defined as static .

abstract class Database {  
    public static $connection;   
    public function __construct( ) {      
        ...  
        $this->connection = mysql_connect( $host, $username, $password );      
    }  
}     
class UserDatabase extends Database {  
    public function verify( ) {
        if ( $this->connection == parent::$connection ) {
            print "true";  
        } else {  
            print "false";  
            print "this:" . $this->connection . " parent:" . parent::$connection;  
        }  
    }    
}  
$instance = new UserDatabase( );  
$instance->verify( );  
// this prints false, as parent::$connection is empty

Does that mean, that my database connection is only set up and stored in memory once and passed on to subclasses as reference without being replicated for each instance?

Is this how you would implement you OOP-correct database interface?

Ignoring your code for a moment and looking only at your description of how this scheme should work... Yes, the database connection would only be set up once for each PHP script and would not be duplicated for each instance.

Whether this is a good idea or not depends on what your subclasses are. Each class should have one responsibility. As long as the subclasses' only responsibility is DB interaction, you're probably fine. (Look at the Repository Pattern for an explanation of how this is commonly done.) If your User class extends Database so that it can store itself, you've crossed a line and are writing classes that will have too many dependencies and responsibilities.

As for your code... Almost every line of your code is wrong. You cannot initialize class variables to the results of a function. Your SQL is wrong. The line $connection ? "connected" : "not connected"; $connection ? "connected" : "not connected"; does nothing. Almost none of that should be done in a constructor. Etc.

That pattern is OK if you're doing nothing else with those classes but database interactions.

Otherwise you may be better off with a Database class that's created once that you can "getInstance()" of each time. Singleton Design Pattern.

http://www.tonymarston.net/php-mysql/singleton.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM