__callStatic
示例:
<?php
//演示通过使用__callStatic这一魔术方法来进行方法的动态创建和延迟绑定
//当调用findByLastname()方法时,可以动态的来生成相应的执行方法
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();
$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',
);
}
class Sales extends ActiveRecord{
protected static $table = 'salesdb';
protected static $fields = array(
'id'=>'int',
'item'=>'varchar',
'qty'=>'int',
);
}
if(assert("select * from custdb where id = 123" == Customer::findById(123)->select)){
echo 'select * from custdb where id = 123'."<br>";
}
if(assert("TODO:set from sql result" == Customer::findById(123)->email)){
echo 'TODO:set from sql result'."<br>";
}
if(assert("select * from salesdb where id = 321" == Sales::findById(321)->select)){
echo 'select * from salesdb where id = 321'."<br>";
}
if(assert("select * from custdb where Lastname = 'Denoncourt'" == Customer::findByLastname('Denoncourt')->select)){
echo "select * from custdb where Lastname = 'Denoncourt'"."<br>";
}
?>
TO BE CONTINUED...
参考文献
魔术方法
登陆发表评论