Link to home
Start Free TrialLog in
Avatar of Robert Saylor
Robert SaylorFlag for United States of America

asked on

php construct

I am passing mysql connection to my class and has been working well. However, I am now starting to use multiple databases.

$linkID = new mysqli(HOST, USER, PASSWORD, DATABASE);
$linkID2 = new mysqli(GOOGLE_HOST, GOOGLE_USER, GOOGLE_PW, 'database');

$myclass = new loader($linkID,$linkID2);

class loader {
        public $linkID;
        function __construct($linkID){ $this->linkID = $linkID; }

}

Open in new window


So my question I know you can only have 1 construct. How can I write the above to be able to call $linkID and $linkID2 ?
ASKER CERTIFIED SOLUTION
Avatar of Marco Gasi
Marco Gasi
Flag of Spain image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Robert Saylor

ASKER

got another method working yay

I called the following outside of the class:
$linkID6 = new mysqli(GOOGLE_HOST, GOOGLE_USER, GOOGLE_PW, 'revenue');
$GLOBALS['linkID6'] = $linkID6;

Open in new window


I am now able to call $GLOBAL['linkID6'] inside my class.
this lead me to thinking GLOBALS
You should always avoid to use global variables. A more correct and secure design pattern is the one I suggested above: that way, DB connections are used internally by the class. Even better should create the connections within the class itself defining them as private in order to better encapsulate them.

Wanting being pities, we could imagine a specific class wich create a new connections based on provided data. This class should be used by any class need to access the database.

Anyway, I discourage you from using GLOBALS.
Why not this

$linkID = new mysqli(HOST, USER, PASSWORD, DATABASE);
$linkID2 = new mysqli(GOOGLE_HOST, GOOGLE_USER, GOOGLE_PW, 'database');

$myclass = new loader($linkID,$linkID2);

class loader {
  public $linkID1;
  public $linkID2;
  function __construct($linkID1, $linkID2)
  {
    $this->linkID1 = $linkID1;
    $this->linkID2 = $linkID2;
  }
}

Open in new window