php 通过__callStatic魔术方法实现方法的动态创建和延迟绑定

<?php
/*
*面向对象魔术方法__callstatic方法的使用
*static 延迟绑定
*/
assert_options(ASSERT_ACTIVE,   1);//允许使用assert()函数
abstract class ActiveRecord{
protected static $table;
protected $fieldvalues;
public $select;


static function findById($id){
$query= "select * from "
.static::$table
." where id = $id";

return self::createDomain($query);
 
}
function __get($fieldname){
return $this->fieldvalues[$fieldname];
}
static function __callStatic($method,$args){
$field=preg_replace('/^findBy(\w*)$/','${1}',$method);
$query = "select * from "
.static::$table
." where $field='$args[0]'";
return self::createDomain($query);
}
private static function createDomain($query){
$klass = get_called_class();
$Customer = new Customer();


$domain = new $klass();

$domain->fieldvalues = array();
$domain->select = $query;
foreach($klass::$fields as $field=>$type){
$domain->fieldvalues[$field] = 'TODO:set from sql result';
}
return $domain;
}
}
class Customer extends ActiveRecord{
protected static $table='custdb';
protected static $fields=array(
'id'=>'int' ,
'email'=>'varchar',
'lastname'=>'varchar'
);
public function getval(){
return self::$fields;
}
}
class Sales extends ActiveRecord{
protected static $table='salesdb';
protected static $fields=array(
'id'=>'int' ,
'item'=>'varchar',
'qty'=>'int'
);
}


 assert("select * from custdb where id = 123" == Customer::findById(123)->select);
 assert("TODO:set from sql result" == Customer::findById(123)->email);
 assert("select * from salesdb where id = 321" == Sales::findById(321)->select);
 assert("select * from custdb where Lastname='Denoncourt'" == Customer::findByLastname('Denoncourt')->select);




?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值