Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class DB { // this class ONLY interacts with the DB
- private $link = null;
- public function __construct($host, $username, $password, $db) {
- $this->link = new PDO('mysql:host='.$host.';dbname='.$db, $username, $password);
- }
- public function doQuery($sql, $values) {
- // do the query using PDO etc
- }
- }
- class Animal {
- private $db = null;
- public function __construct(\DB $db) { // here we typehint for the db class we need
- $this->db = $db; // but this class has no idea how to construct it
- }
- public function poop() {
- // all animals do it, basically constantly.
- }
- public function save() {
- // use $this->db to write to database
- }
- }
- class Dog extends Animal {
- public $breed = 'Mutt';
- public function __construct(\DB $db, $breed = 'Mutt') {
- parent::_construct($db);
- $this->breed = $breed;
- $this->poop(); // dogs...
- }
- }
- // make the db connection
- $db = new DB('localhost', 'user', 'password', 'animalDb');
- // pass it to the class that will use it.
- $myDog = new Dog($db, 'German Shorthair Pointer');
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement