This is a discussion on Problems referencing derived variables within the PHP General forums, part of the PHP Programming Forums category; Is it possible to reference a variable that is instantiated within the parent class: class Db { public connectionId; public function ...
|
|||||||
| FAQ | Members List | Calendar | Search | Today's Posts | Mark Forums Read |
|
|||
|
Is it possible to reference a variable that is instantiated within the
parent class: class Db { public connectionId; public function connect($connectString) { $this->connectionId = databaseDriverConnect($connectString); } public function query($queryString) { . . . }; public function fetch() { . . . }; .. . . } class TableGenerator extends Db { ??? reference to the one and only connectionId ??? /* - make the query needed to draw a table - draw the table */ .. . . } After connecting to the database I want to be able to share the connectionId inside the TableGenerator class or some other derived class: $db = new Db(); $db->connect("SomeConnectString"); $tg = new TableGenerator(); $tg->... draw some table without connecting again ... Until now I had to make the $db instance global and use it for making queries inside non derived/nonderived classes, now I want to make it more OO. I'd like to point out that I need only one connection per request and several instances like for example TableGenerator, GraphGenerator,... Is this approach possible and is it the right one?? Thanks. |
|
|||
|
Using a single instance for the database makes sense, since it will
likely be accessed by many different components and objects. This is usually known as the singleton pattern. This can be done as a global, or something like a static method that returns the instance. On Mar 22, 7:57 am, "selaz" <ales.z...@gmail.com> wrote: > Is it possible to reference a variable that is instantiated within the > parent class: > > class Db { > public connectionId; > public function connect($connectString) { $this->connectionId = > databaseDriverConnect($connectString); } > public function query($queryString) { . . . }; > public function fetch() { . . . }; > . . . > > } > > class TableGenerator extends Db { > ??? reference to the one and only connectionId ??? > /* > - make the query needed to draw a table > - draw the table > */ > . . . > > } > > After connecting to the database I want to be able to share the > connectionId inside the TableGenerator class or some other derived > class: > > $db = new Db(); > $db->connect("SomeConnectString"); > > $tg = new TableGenerator(); > $tg->... draw some table without connecting again ... > > Until now I had to make the $db instance global and use it for making > queries inside non derived/nonderived classes, now I want to make it > more OO. I'd like to point out that I need only one connection per > request and several instances like for example TableGenerator, > GraphGenerator,... Is this approach possible and is it the right one?? > > Thanks. |