|
继承
- <?php
- /*
- 继承
- 直观目标:
- 解决代码的重用
- 实现步骤:
- 1. 提取重复的代码
- 2. 建立联系, extends
- */
- // 父类 - 基类
- class Animal
- {
- public $money = 100;
- public function eat()
- {
- echo "{$this->name} 开始吃饭饭!<br>";
- }
- public function drink()
- {
- echo "{$this->name} 开始喝水水!<br>";
- }
- }
- // 子类 - 派生类 - 继承者
- class Dog extends Animal
- {
- public $name = '';
- public function __construct($name)
- {
- $this->name = $name;
- }
- }
- class Cat extends Animal
- {
- public $name = '';
- public function __construct($name)
- {
- $this->name = $name;
- }
- }
- class Pig extends Animal
- {
- public $name = '';
- public function __construct($name)
- {
- $this->name = $name;
- }
- }
- $dog = new Dog('旺财');
- $cat = new Cat('咖啡猫');
- $pig = new Pig('佩奇');
- $dog->eat();
- $cat->eat();
- $pig->eat();
- $dog->drink();
- $cat->drink();
- $pig->drink();
- $dog->money = $dog->money - 2;
- echo '<pre>';
- print_r($dog);
- echo '</pre>';
- echo '<pre>';
- print_r($cat);
- echo '</pre>';
- echo '<pre>';
- print_r($pig);
- echo '</pre>';
- // 使用了继承,父类拥有的所有属性和方法,子类都有。
复制代码 mysqli
- <?php
- define('DB_HOST', 'localhost');
- define('DB_USER', 'root');
- define('DB_PASSWD', 'jiege');
- define('DB_NAME', 'test');
- define('DB_PORT', '3306');
- // $mysql = new MySQLi(DB_HOST, DB_USER, DB_PASSWD, DB_NAME, DB_PORT);
- // // 组装SQL
- // $sql = 'select * from user limit 1';
- // // 发送执行
- // $result = $mysql->query($sql);
- // // 检索结果
- // $rows = $result->fetch_all(MYSQLI_ASSOC);
- // echo '<pre>';
- // print_r($rows);
- // echo '</pre>';
- class Model
- {
- public $mysql = null;
- public $result = null;
- public function __construct()
- {
- // mysql 的连接
- $this->mysql = new MySQLi(DB_HOST, DB_USER, DB_PASSWD, DB_NAME, DB_PORT);
- }
- public function find(int $id)
- {
- // 组装SQL
- $sql = "select * from `{$this->table}` where `id` = {$id} limit 1";
- echo $sql . '<br>';
- $this->query($sql);
- return $this->fetch();
- }
- public function query($sql)
- {
- // 发送执行
- $this->result = $this->mysql->query($sql);
- }
- public function fetch() : array
- {
- // 检索结果
- $rows = $this->result->fetch_all(MYSQLI_ASSOC);
- return $rows;
- }
- }
- class User extends Model
- {
- public $table = 'user';
- }
- $user = new User();
- $list = $user->find(1);
- echo '<pre>';
- print_r($list);
- echo '</pre>';
- class Products extends Model
- {
- public $table = 'products';
- }
- $product = new Products();
- $list = $product->find(2);
- echo '<pre>';
- print_r($list);
- echo '</pre>';
复制代码
|
|