Correction status:Uncorrected
Teacher's comments:
<?php /* 重载 * */ class Test{ public function __call($name, $arguments) { $args= implode(',', $arguments); return '方法名:'.$name.'<br>参数:'.$args.'<br>'; } //创建私有方法 private function select(){ return __METHOD__; } public static function __callStatic($name, $arguments) { $args = implode(',', $arguments); return '方法名:' . $name . '<br>参数:' . $args . '<br>'; } } $test=new Test(); echo $test->show(),'<br>'; echo $test->show(), '<br>';
点击 "运行实例" 按钮查看在线实例
2、静态继承
<?php /** * call_user_func_array():执行方法或回调函数 * call_user_func_array(函数/方法[, 参数数组]) */ //场景一:计算2个整数之和 echo call_user_func_array(function($m,$n){return $m+$n;}, [10,20]), '<hr>'; //场景二:执行对象方法 class Hello1{ public function add($m, $n) { return $m + $n; } } echo call_user_func_array([new Hello1(),'add'], [100,200]),'<hr>'; //场景3:执行类中静态方法 class Hello2{ public static function add($m, $n) { return $m + $n; } } echo call_user_func_array(['Hello2', 'add'], [200, 200]), '<hr>';
点击 "运行实例" 按钮查看在线实例
3、链式调用,类似thinkphp
<?php /** * 方法重载的实战案例: 模拟ThinkPHP5.1中的数据库链式操作 * 用方法重载实现方法跨类调用 */ //Db::table()->fields()->where()->select(); require 'Query.php'; class Db{ public static function __callStatic($name, $arguments) { return call_user_func_array([new Query(),$name], $arguments); } } echo '<pre>'; $result=Db::table('staff') ->fields('staff_id,name,salary') ->where('salary>2000') ->select(); print_r($result);
点击 "运行实例" 按钮查看在线实例
<?php class Query{ private $sql=[]; private $pdo=null; //构造方法:连接数据库 public function __construct() { $this->pdo=new PDO('mysql:host=127.0.0.1;dbname=php','root','root123'); } //table public function table($table){ $this->sql['table']=$table; return $this; } //fields public function fields($fields){ $this->sql['fields'] = $fields; return $this; } //where public function where($where){ $this->sql['where']=$where; return $this; } //执行查询,终极方法 public function select(){ $sql="SELECT {$this->sql['fields']} FROM {$this->sql['table']} WHERE {$this->sql['where']}"; $stmt= $this->pdo->prepare($sql); $stmt->execute(); return $stmt->fetchAll(PDO::FETCH_ASSOC); } }
点击 "运行实例" 按钮查看在线实例