Reputation: 4288
I have a PHP class-- a generic ODBC database interface. While the methods will never change (because it uses PDO), the connection string will. To avoid having the user pass in an entire connection string manually or specify an ODBC driver to be placed into a connection string, I extend the class and create a SQL Server specific version.
Generic PDO ODBC Driver
class PDO_ODBC implements DBDriver{
private $driver;
private $connection_string;
public function connect(){
if(!$this->driver || !$this->connection_string){
throw new \Exception("Invalid connection string or database driver.");
}
}
}
SQL Server Specific Version
class PDO_ODBC_SQL_Server extends PDO_ODBC{
public function __construct(){
$this->driver = 'SQL Server';
$this->connection_string = 'odbc:Driver={[Driver]};Server=[Host];Database=[DBName];Uid=[Username];Pwd=[Password]';
}
}
The problem is, when I create a new PDO_ODBC_SQL_Server
object and call connect()
, the exception is thrown because $this->driver
and $this->connection_string
doesn't exist. But how can this be? If I use print_r
, I see both of those properties. One thing to note is that print_r
also shows the namespace of the class for all properties except the driver and connection string, as shown here: http://pastebin.com/qh40eDpa. In fact, there are separate variables of connection string and driver under the namespace.
How can I fix this and prevent the exception from being thrown, while still being able to use a similar design pattern by extending the base ODBC class? If not, then the alternative is to allow for the developer to pass in a driver and connection string...
Note, I've omitted most of the private variables in the code sample above for brevity. Both of these classes are located in separate files and are under the namespace Lib\Database
Upvotes: 1
Views: 452
Reputation: 9907
Make the class properties protected
or make getters and setters if you want to keep them private. Private properties can only be accessed from the class in which they are declared, not derived classes.
class PDO_ODBC implements DBDriver{
protected $driver;
protected $connection_string;
public function connect(){
if(!$this->driver || !$this->connection_string){
throw new \Exception("Invalid connection string or database driver.");
}
}
}
http://php.net/manual/en/language.oop5.visibility.php#language.oop5.visibility-members
Upvotes: 1