Advertisement
Guest User

Untitled

a guest
May 24th, 2016
229
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.05 KB | None | 0 0
  1. class DB { // this class ONLY interacts with the DB
  2.     private $link = null;
  3.     public function __construct($host, $username, $password, $db) {
  4.         $this->link = new PDO('mysql:host='.$host.';dbname='.$db, $username, $password);
  5.     }
  6.  
  7.     public function doQuery($sql, $values) {
  8.         // do the query using PDO etc
  9.     }
  10. }
  11.  
  12. class Animal {
  13.     private $db = null;
  14.     public function __construct(\DB $db) { // here we typehint for the db class we need
  15.         $this->db = $db;                   // but this class has no idea how to construct it
  16.     }
  17.  
  18.     public function poop() {
  19.         // all animals do it, basically constantly.
  20.     }
  21.  
  22.     public function save() {
  23.         // use $this->db to write to database
  24.     }
  25. }
  26.  
  27. class Dog extends Animal {
  28.     public $breed = 'Mutt';
  29.     public function __construct(\DB $db, $breed = 'Mutt') {
  30.         parent::_construct($db);
  31.         $this->breed = $breed;
  32.         $this->poop(); // dogs...
  33.     }
  34. }
  35.  
  36. // make the db connection
  37. $db = new DB('localhost', 'user', 'password', 'animalDb');
  38.  
  39. // pass it to the class that will use it.
  40. $myDog = new Dog($db, 'German Shorthair Pointer');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement