After looking around most of last night and all of this morning, I find myself here.

I am looking to include a database connection within another class. From what I've read creating a connection within a class is bad? Can someone help me out or even point me in the direction of where I can find the relevant answer?

Thanks.

Recommended Answers

Yes, just put it in a variable, just like you did with name.

Jump to Post

All 3 Replies

From what I've read creating a connection within a class is bad?

Not necessarily. I would just pass a MySQLi or PDO object as a parameter to the class' constructor, and store it in a private variable.

So like this, providing I called me connection $mysqli?

class person {
  var $name;
  function __construct($mysqli, $persons_name) {
    $this->name = $persons_name;
  }
}

Yes, just put it in a variable, just like you did with name.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.