将SQL Object传递给新类

I have an active mysql object that contains my conections etc.. $db->query(my query). I want to pass this object into a new class so i don't have to create the object again

How would i go about passing it into the new class so it's still active?

class NewClass {
  var $db;
  function __construct($db) {
   $this->db=$db;
 }

}

Thoughts?

Your example seems valid to me. It's one of the three types of dependency injection Martin Fowler identifies:

  • Constructor
  • Setter
  • Interface

If you wanted, for example, to use setter injection instead of constructor injection, create a setter method on your class to accept the database parameter. It might be worth making the property private too, in order to prevent other code from using objects of NewClass as providers of the database object.

class NewClass {
  private $db;
  public function setDb($db) {
    $this->db=$db;
  }
}