Blogger Information
Blog 28
fans 0
comment 0
visits 15723
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
oop编程 委托 和回调
︷肉園耔︷
Original
497 people have browsed it
  1. /**
  2. * Created by PhpStorm.
  3. * User: Administrator
  4. * Date: 2021-10-10
  5. * Time: 19:26
  6. */
  7. //被委托的类
  8. class Query{
  9. //创建类的唯一实例 pdo对象
  10. private static $db;
  11. protected $table;
  12. protected $field;
  13. protected $limit;
  14. //private 私有 阻止此类在外部进行实例化
  15. private function __construct(){
  16. }
  17. static function connect($dsn,$username,$pwd){
  18. //创建PDO类的唯一实例 PDO对象
  19. if(is_null(static::$db)){
  20. static::$db= new PDO($dsn,$username,$pwd);
  21. }
  22. //返回query实例
  23. return new static();
  24. }
  25. public function table($table){
  26. $this->table=$table;
  27. return $this;
  28. }
  29. public function field($field){
  30. $this->field=$field;
  31. return $this;
  32. }
  33. public function table($limit){
  34. $this->limit=$limit;
  35. return $this;
  36. }
  37. public function getSql(){
  38. return sprintf('SELECT %s FROM %s LIMIT %d ', $this->field, $this->table,$this->limit);
  39. }
  40. public function select(){
  41. return static::$db->query($this->getSql())->fatchaAll(POD::FETCH_ASSOC);
  42. }
  43. class Db{
  44. static function __callStatic($method,$args){
  45. $dsn='mysql:host=39.105.79.62;dbname=news';
  46. $usernmae='miujue';
  47. $pwd='zhoujielun521';
  48. //获取到被委托的类query实例
  49. $query=Query::connect($dsn,$username,$pwd);
  50. call_user_func([$query,$method],...$args);
  51. }
  52. }
  53. $res= DB::table('cate')->field('catname,catid')->limit(5)->select();
  54. echo '<pre>';
  55. print_r($res);
Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post