如何防止调用不存在的方法而出错,使用__call魔术重载方法.
<?php class HandsonBoy { private $name = ‘chenqionghe‘; private $age = 18; 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; } } } $a = new HandsonBoy(); $a->make(5); $a->make(5,6);
<?php abstract class ActiveRecord { protected static $table; protected $fieldvalue; 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) { $class = get_called_class();//获取静态方法调用的类名 $domain = new $class(); $domain->fieldvalues = array(); $domain->select = $query; foreach ($class::$fields as $field => $type) { $domain->fieldvalues[$field] = ‘TODO:set from sql result by ‘ . $field; } return $domain; } } class Customer extends ActiveRecord { protected static $table = ‘custdb‘; protected static $fields = array( ‘id‘ => ‘int‘, ‘email‘ => ‘int‘, ‘lastname‘ => ‘varchar‘ ); } class Sales extends ActiveRecord { protected static $table = ‘salesdb‘; protected static $fields = array( ‘id‘ => ‘int‘, ‘item‘ => ‘varchar‘, ‘qty‘ => ‘int‘ ); } var_dump(Customer::findById(123)->select); var_dump(Customer::findById(123)->email); var_dump(Sales::findByLastname(‘Denoncourt‘)->select);
原文:http://www.cnblogs.com/chenqionghe/p/4735703.html