Correction status:qualified
Teacher's comments:
1.编程: 单例模式:
<?php //1.编程: 单例模式 echo '//1.编程: 单例模式','<hr>'; class Student { //private $name; //private $age; private static $instance = null; //private 外部就没办法实例化了 private function __construct() { //$this->name = $name; //$this->age = $age; } //克隆方法私有化,外部也就无法访问了 private function __clone() { // TODO: Implement __clone() method. } //外部仅通过公共的静态方法创建实例 public static function getInstance() { //检测当前类的属性是否已经保存了当前类的实例 if (self::$instance == null) { self::$instance == new self(); } //返回当前的实例 return self::$instance; } } $obj1 = Student::getInstance(); $obj2 = Student::getInstance(); var_dump($obj1,$obj2); echo '<br>'; var_dump($obj1 === $obj2); echo '<br><br>';
点击 "运行实例" 按钮查看在线实例
2.编程: MVC的实现原理:
Model:
<?php class Model { private $pdo = null; public $result = []; //连接数据库 public function __construct($dbname,$user,$pass) { $this->pdo = new \PDO('mysql:host=127.0.0.1;dbname='.$dbname,$user,$pass); } //查询 public function select($table,$num) { $stmt = $this->pdo->prepare("SELECT `id`,`name`,`age` FROM {$table} LIMIT :num"); //执行查询 查询10条信息 value:$num $stmt->bindValue(':num',$num,PDO::PARAM_INT); $stmt->execute(); $this->result = $stmt->fetchAll(PDO::FETCH_ASSOC); } }
点击 "运行实例" 按钮查看在线实例
View:
<?php /** * Created by PhpStorm. * User: T3rdW * Date: 2018/9/8 * Time: 14:26:34 */ class View { public $data = []; public function __construct($data) { $this->data = $data; } public function getData() { return $this->data; } public function display($data) { $table = ' <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>MVC模式</title> <style> table,th,td{ border: 1px solid black; } table { border-collapse: collapse; width: 600px; margin: 30px auto; text-align: center; } table tr:first-child { background-color: #39FF1B; } table caption { font-size: 1.5em; margin-bottom: 15px; } </style> <table> <caption>员工信息表</caption> <tr> <th>ID</th> <th>姓名</th> <th>年龄</th> </tr>'; foreach ($data as $user) { $table .= '<tr>'; $table .= '<td>'.$user['id'].'</td>'; $table .= '<td>'.$user['name'].'</td>'; $table .= '<td>'.$user['age'].'</td>'; $table .= '</tr>'; } $table .= '</table></body></html>'; echo $table; } }
点击 "运行实例" 按钮查看在线实例
Controller:
<?php /** * Created by PhpStorm. * User: T3rdW * Date: 2018/9/8 * Time: 14:44:59 */ class Controller { public function index($num) { require 'Model.php'; $model = new Model('user','root','root'); $model->select('name',$num); $result = $model->result; require 'View.php'; $view = new View($result); $data = $view->getData(); $view->display($data); } }
点击 "运行实例" 按钮查看在线实例