博客列表 >第十一课— 方法重载与静态继承 2018年9月4日 20时00分

第十一课— 方法重载与静态继承 2018年9月4日 20时00分

空白
空白原创
2018年09月06日 13:53:06721浏览

实例

<?php
// 链式查询
// 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);
	}
}

$res = Db::table('user')
		->fields('id, name, salary')
		->where('salary > 5000')
		->select();

// 用表格将查询结果格式化输出
$table = '<table border="1" cellpadding="5" cellspacing="0" width="60%" align="center">';
$table .= '<caption style="font-size: 1.5rem;margin:15px;">员工信息表</caption>';
$table .= '<tr bgcolor="#eee"><th>ID</th><th>姓名</th><th>年龄</th><th>工资</th></tr>';

foreach ($res as $user) {
    $table .= '<tr align="center">';
    $table .= '<td>'.$user['id'].'</td>';
    $table .= '<td>'.$user['name'].'</td>';
    $table .= '<td>'.$user['salary'].'</td>';
    $table .= '</tr>';
}

$table .= '</table>';
$num = '<p style="text-align: center"> 共计:  <span style="color:red">'.count($res).'</span>   条记录</p>';
echo $table, $num;

运行实例 »

点击 "运行实例" 按钮查看在线实例

实例

<?php
// 数据库查询类

class Query
{
	// 保存sql语句
	private $sql = [];

	// 数据库连接对象
	private $pdo;

	// 构造方法连接数据库
	public function __construct()
	{
		$this -> pdo = new PDO('mysql:host=127.0.0.1;dbname=test','root','');
	}

	// table() 获取表名
	public function table($table)
	{
		$this -> sql['table'] = $table;
		// 返回当前类实例对象,便于链式调用该对象的其它方法
		return $this;
	}

	// fields() 获取字段列表
	public function fields($fields)
	{
		$this -> sql['fields'] = $fields;
		// 返回当前类实例对象,便于链式调用该对象的其它方法
		return $this;
	}

	// where() 获取sql语句where条件
	public function where($where)
	{
		$this -> sql['where'] = $where;
		// 返回当前类实例对象,便于链式调用该对象的其它方法
		return $this;
	}

	// select()终级方法:执行查询
	public function select()
	{
		//拼装SELECT查询语句
		$sql = "SELECT {$this -> sql['fields']} FROM {$this -> sql['table']} WHERE {$this -> sql['where']}";
		// sql预处理
		$stmt = $this->pdo->prepare($sql);
		// 查询
		$stmt -> execute();
		return $stmt ->fetchAll(PDO::FETCH_ASSOC);
	}
}

运行实例 »

点击 "运行实例" 按钮查看在线实例

1.png

后期静态绑定的原理:使用static::访问该方法,调用该方法时始终指向静态方法的调用者

使用场景分析:在子类重写父类方法时使用静态绑定,子类便可访问到自己重写的方法


声明:本文内容转载自脚本之家,由网友自发贡献,版权归原作者所有,如您发现涉嫌抄袭侵权,请联系admin@php.cn 核实处理。
全部评论
文明上网理性发言,请遵守新闻评论服务协议