简介
__call 当要调用的方法不存在或权限不足时,会自动调用__call 方法。
__callStatic 当调用的静态方法不存在或权限不足时,会自动调用__callStatic方法。
当调用一个不可访问的方法时 (如未定义,或者不可见)时,__call()会被调用。其中 name参数时要调用的方法名称。 arguments参数时一个数组,包含着要传递给方法的参数
__call代码
<?php
class Tuzi{
public function __call($name,$arguments){
switch(count($arguments)){
case 2:
echo $arguments[0]*$arguments[1],PHP_EOL;
break;
case 3:
echo array_sum($arguments),PHP_EOL;
break;
default:
echo '参数不对',PHP_EOL;
break;
}
}
}
$tuzi = new Tuzi;
$tuzi -> make(5,6);
__callStatic代码
<?php
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);
echo $field."<br/>";
$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'
);
}
echo Customer::findById(123) -> select;//链式操作
// assert("select * from custdb where id=123" ==
// Customer::findById(123) -> select);