Abstract and normal classes in PHP

Normal and abstract classes in PHP differ from each other for a simple fact: abstract classes can't be instantiated using the new operator as for normal classes. Generally speaking, abstract classes are used as a mould for other classes. An abstract class is always more generic than a normal class, and this is the main feature that describes abstract classes.

A typical implementation for abstract classes is the underlying structure that handles database connections:

abstract class Database
{

    const DB_USER = 'test';
    const DB_HOST = 'localhost';
    const DB_PWD = 'test';
    const DB_NAME = 'test';

   abstract  protected function connect();

   abstract  protected function disconnect();

}

Then we can extend this class, for example with a more concrete class:

class MySQL extends Database
{

    protected $_connection;

    public function __construct()
    {

    
        $this->connect();

    }

    protected function connect()
    {

        $this->_connection = mysql_connect(self::DB_HOST, self::DB_USER, self::DB_PWD);

        mysql_select_db(self::DB_NAME, $this->_connection;

    }

   protected function disconnect()
   {

          return @mysql_close($this->_connection);

   }

    public function __destruct()
    {

        $this->disconnect();

    }

}

Once you have extended the abstract class, you can use the extended class as usual:

$mysql = new MySQL();

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.