批改狀態(tài):合格
老師批語:
使用方法重載與call_user_func_array()模擬TP框架的鏈?zhǔn)讲樵儯?/strong>
Db類文件:
<?php require 'Qurey.php'; class Db{ public static function __callStatic($name, $arguments) { // call_user_func_array([類,方法],[數(shù)組]) return call_user_func_array([(new Qurey()),$name],$arguments); } } // table(表名)fields(字段')where(條件)select()執(zhí)行語句方法 $result = Db::table('lianxi')->fields('id,name')->where('id > 0')->select(); print_r($result);
點擊 "運行實例" 按鈕查看在線實例
Qurey類文件:
<?php class Qurey{ // sql 語句 private $sql = []; // 連接數(shù)據(jù)庫 private $pdo = null; // 構(gòu)造方法,連接數(shù)據(jù)庫 public function __construct() { // 連接數(shù)據(jù)庫并返回pdo對象 $this->pdo = new PDO('mysql:host=127.0.0.1;dbname=php','root','root'); } // table 獲取數(shù)據(jù)庫表名 public function table($table){ $this->sql['$table'] = $table; return $this; } // table 獲取數(shù)據(jù)庫字段列表 public function fields($fields){ $this->sql['fields'] = $fields; return $this; // } //where 獲取sql語句查詢條件 public function where($where){ $this->sql['where'] = $where; return $this; } // 執(zhí)行查詢結(jié)果 public function select(){ $sql = "SELECT {$this->sql['fields']} FROM {$this->sql['$table']} WHERE {$this->sql['where']}"; // 預(yù)處理對象 $stmt = $this->pdo->prepare($sql); // 執(zhí)行sql語句 $stmt->execute(); // 獲取結(jié)果集的關(guān)聯(lián)數(shù)據(jù) return $stmt->fetchAll(PDO::FETCH_ASSOC); } }
點擊 "運行實例" 按鈕查看在線實例
執(zhí)行結(jié)果:
2、后期靜態(tài)綁定的原理與使用場景分析:
場景分析:
1、定義靜態(tài)成員
2、后期靜態(tài)綁定
后期靜態(tài)綁定的原理代碼:
class One { public static function hello() { return __METHOD__; // 返回當(dāng)前方法名 } public static function world() { // 如果使用 self來訪問靜態(tài)方法,在子類中調(diào)用world()時,調(diào)用的方法是父類的方法,而子類world()方法并沒有繼承下來, // return self::hello(); // 使用static 關(guān)鍵字會讓hello()方法進(jìn)行繼承下去,可以在子類來訪問子類的靜態(tài)方法 return static::hello(); } } class Two extends One { public static function hello() { return __METHOD__; // 返回當(dāng)前方法名 } } echo Two::hello(); // 調(diào)用的是子類的靜態(tài)方法 // 在子類Two中將父類中的hello()進(jìn)行重寫,在調(diào)用world()時,本意是想調(diào)用子類中已重寫的方法hello(), // 怎么辦? 在父類訪問world()方法的hello()方法,添加stctic關(guān)鍵字就可以解決子類可以訪問父類繼承下來的靜態(tài)方法 echo Two::world(); // 因為在父類添加了 stctic關(guān)鍵字所以他的最終調(diào)用的是子類的方法:結(jié)果為:Two::hello
點擊 "運行實例" 按鈕查看在線實例
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號