tags:

views:

70

answers:

3

here is my sample class to why i want to nest.

include("class.db.php");

class Cart {

function getProducts() {

//this is how i do it now. 
//enter code here`but i dont want to redeclare for every method in this class. 
//how can i declare it in one location to be able to use the same variable in every method?
$db = new mysqlDB;


$query = $db->query("select something from a table");
return $query

}

}
A: 

You could have something like this

<?php
     class cart 
    {
          protected $database;

          function __construct()
          {
                $this->database = new mysqlDB;
          }

          function getProducts()
          {
               $this->database->query("SELECT * FROM...");
          }
    }
?>

__construct is the function that is called when you instantiate a class.

Foxtrot
I would recommend against this because it would be a problem if you already connected to the database in another part of the code, or wanted to make multiple carts. Use the answer below because it injects the dependency through the constructor.
Lotus Notes
A: 

Isolate the common code to each method/function into another private internal method/function.

If you need to have it run once automatically for the object when it's created, this is what __construct is for.

Weston C
yep thanks , got it
michael
+8  A: 

Take advantage of properties.

class Cart {

    private $db;

    public function __construct($db) {
        $this->$db = $db;
    } 

    public function getProducts() {
        $query = $this->db->query( . . .);
        return $query;
    }

}

You'll create the database object outside of your class (loose coupling FTW).

$db = new MysqlDb(. . .);
$cart = new Cart($db);
Jeremy Kendall