php mysql连贯操作_php __call()方法实现数据库连贯操作

使用__call()方法来实现数据库连贯操作

// 使用__call()方法来实现数据库连贯操作

// 申明一个Db类(数据库操作类)的简单操作模型

class Db{

private $sql = array(

"field" => "",

"where" => "",

"order" => "",

"limit" => "",

"group" => "",

"having" => "",

);

// 连贯操作调用field() where() order() limit() group() having()方法,组合sql语句

function __call($methodName,$args){

// 将第一个参数(代表不存在方法的方法名称),全部转成小写方式,获取方法名称

$methodName = strtolower($methodName);

// 如果调用的方法名和成员属性数组$sql下标对应上,则将第二个参数给数组中下标对应的元素

if(array_key_exists($methodName,$this->sql)){

$this->sql[$methodName] = $args[0];

}else{

echo '调用类'.get_class($this).'中的方法'.$methodName.'()不存在';

}

// 返回自己对象,则可以继续调用本对象中的方法,形成连贯操作

return $this;

}

// 输出连贯操作后组合的一个sql语句,是连贯操作最后的一个方法

function select(){

echo "SELECT {$this->sql['field']} FROM user {$this->sql['where']} {$this->sql['order']} {$this->sql['limit']} {$this->sql['group']}

{$this->sql['having']}";

}

}

$db = new Db();

// 连贯操作

$db->field('sex, count(sex)')

->where('where sex in ("男","女")')

->group('group by sex')

->having('having avg(age) > 25')

->select();

?>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值