Restricting Class Instances (PHP 5)
Posted: Thu Jul 03, 2008 5:14 pm
I have a MySQL database wrapper that restricts the implementation of using a database wrapper for another database like Oracle for instance because the class is called Default_Database and the reason for this is it is used throughout the framework I am working on for different classes, therefore using MySQL_Database would not permit the swapping of databases for whatever reason someone may have.
If I change my Default_Database name to MySQLi_Database and then extend the class like so:
[Example 1]
This allows me to easily set a default database for whatever database I want to use but the only problem is if somebody chooses to use MySQLi_Database they can create another connection to the same database depending on what parameters have been supplied in the following:
[Example 2]
for the MySQLi_Database class.
No matter what is used here there is going to be a problem, passing no parameters will attempt a connection based default values and passing wrong values will cause errors, either way we either connect to 2 different databases when not required, connect to the same database twice (if persistent connections are not enabled), or plain and simply get lots of errors.
As the MySQLi_Database class has lots of useful methods that return values, I want this functionality to be easily extended should somebody need to connect to 2 different databases like in [Example 1] but I want to stop people creating an instance of MySQLi_Database itself. Is this at all possible?
Cutting a long story short, I want to be able to extend a class that is restricted so that the only way it can be used is when it is extended.
If I change my Default_Database name to MySQLi_Database and then extend the class like so:
[Example 1]
Code: Select all
class Default_Database extends MySQLi_Database {
private function _connect () {
self::$_db->real_connect('127.0.0.1', 'root', '*****', '*****');
}
}[Example 2]
Code: Select all
self::$_db->real_connect('127.0.0.1', 'root', '*****', '*****');No matter what is used here there is going to be a problem, passing no parameters will attempt a connection based default values and passing wrong values will cause errors, either way we either connect to 2 different databases when not required, connect to the same database twice (if persistent connections are not enabled), or plain and simply get lots of errors.
As the MySQLi_Database class has lots of useful methods that return values, I want this functionality to be easily extended should somebody need to connect to 2 different databases like in [Example 1] but I want to stop people creating an instance of MySQLi_Database itself. Is this at all possible?
Cutting a long story short, I want to be able to extend a class that is restricted so that the only way it can be used is when it is extended.