I’m trying to develop a system using MySQL and PHP. I’m using mysqli* function using OOP. The problems I’m having is the next one:
I have a class for connect to the database:
<?php
class Conexion{
$this->linkDb = new mysqli("127.0.0.1", "user", "pass");
if($this->linkDb){
$this->linkDb->select_db("test");
return TRUE;
}
else{
return FALSE;
}
} // End of class Conexion
?>
I have several classes to retrieve and store data in my database, for example:
<?php
class Product{
public function listProducts()
{
$query = "SELECT * FROM products";
$rsProducts = $linkDb->query($query);
if($rsProducts){
// ....
}
else{
// ....
}
}
}
?>
And I use this classes in the next file (main):
<?php
function __autoload($className)
{
require_once("./class/$className.php");
}
$cnx = new Conexion();
$prd = new Products();
if($prd->listProducts()){
echo "OK";
}
else{
echo "Wrong...";
}
?>
When I try to run this file, I get the next error:
Fatal error: Call to a member function query() on a non-object in /home/emco/training/phpmysqli/class/Products.php on line 8
I know the error is because of the scope of $linkDb in the method listProducts(). My question is, How can I do to make the link of the conexion available in all the functions of my classes? Do I have to make a conexion link in each of the functions of my classes? What’s the correct way to do this?
You can either pass the
$cnxobject to each method call ofProducts, or establish it as a property ofProducts. (A third method would be to declareglobal $linkDbinside methods, but it is clearer to use a dependency injection.)Example 1: Inject the connection into the constructor and keep it as a property to
ProductsExample 2: Pass
$cnxto each method call ofProductswhere it is needed