1

Hi I am trying to rebuild my code with mysqli instead of mysql but I have a problem with mysql in a php class:

$db = new mysqli('localhost','user','password','dbname');

require_once('classes/some_class.php');
$some_class = new some_class();

in some_class.php:

 class some_class {
  function __construct() { $db->query('blablabla'); }
 }

This ist not working but: If I add $db = new ...in some_class.php it works!

So some_class.php don't know the database connection :/

Gray
  • 7,050
  • 2
  • 29
  • 52
Wikunia
  • 1,564
  • 1
  • 16
  • 37
  • Is `$db->query(...)` contained in a function or class method? – ComFreek Oct 05 '13 at 16:04
  • 2
    It is not some_class but rather you don't know of [variable scope](http://stackoverflow.com/questions/16959576/reference-what-is-variable-scope-which-variables-are-accessible-from-where-and) – Your Common Sense Oct 05 '13 at 16:04

2 Answers2

1

some_class() is dependent upon your $db.

You have several options;

pass the dependency in as an argument:

$db = new mysqli('localhost','user','password','dbname');
// that could be in a different file

class some_class {
private $db;
function __construct($db) 
{
$this->db=$db; 
}
// eg - do a query
function getStuff($qry){
$this->db->query($qry); 
}
}

OR

As you said, have someclass instantiate the db connection

OR

Use a global variable.

There are pros and cons concerning each. There are other ways too. If you want to really understand the implications of each, I suggest you find yourself at least one really good OOP book. This stuff is clever but finding the right answer for each situation does not come cheap.

Cups
  • 6,901
  • 3
  • 26
  • 30
1

Your variable is out of scope, some_class has no idea what $db is. You need to pass $db as an argument. You can do this when instantiating the class.

$db = new mysqli('localhost','user','password','dbname');

require_once('classes/some_class.php');
$some_class = new some_class($db);
 //Pass $db here -------------^ to the constructor

Then this will work.

class some_class {
    function __construct($db) { $db->query('blablabla'); }
}
//You receive $db here ---^
Scott Helme
  • 4,786
  • 2
  • 23
  • 35