ksmatthews Posted August 2, 2009 Share Posted August 2, 2009 Hi There, I am using a class that makes a lot of use of a DB object (see code below). Currently I instantiate the object within each function which has to be repeated for each function. How can I avoid this ? I have tried to instantiate the object OUTSIDE of the class but it is not visible from within the functions .... // Access Control class require_once('class.database.php'); class Access_control { // Declare class members, PHP 5 style private $uname = ""; private $pword = ""; // constructor public function Access_control($uname, $pword) { $this->uname = $uname; $this->pword = $pword; } public function func_1() { // instantiate DB class object $myDB = new mySQLDatabase(DB_NAME, USER_NAME, PASSWORD, CONNECT_SQL_ERROR, URL); // code here $myDB->Close_DB(); } public function func_2() { // instantiate DB class object $myDB = new mySQLDatabase(DB_NAME, USER_NAME, PASSWORD, CONNECT_SQL_ERROR, URL); // code here $myDB->Close_DB(); } // etc } Thanks, Steven M Link to comment https://forums.phpfreaks.com/topic/168486-object-visibility-within-a-class/ Share on other sites More sharing options...
trq Posted August 2, 2009 Share Posted August 2, 2009 The easiest way is just to instantiate your db connection and assign it to a property within your construct. The more portable (as long as your db resource abides to some interface) solution is to pass your database resource to your construct as an argument. Link to comment https://forums.phpfreaks.com/topic/168486-object-visibility-within-a-class/#findComment-888824 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.