一 反射的使用:
复制代码 代码如下:
name=$name;
}
}
interface module{
function execute();
}
class ftpmodule implements module{
function sethost($host){
print ftpmodule::sethost():$host\n;
}
function setuser($user){
print ftpmodule::setuser():$user\n;
}
function execute(){
//something
}
}
class personmodule implements module{
function setperson(person $person){
print personmodule::setperson:{$person->name}\n;
}
function execute(){
//something
}
}
class modulerunner{
private $configdata
=array(
personmodule=>array('person'=>'bob'),
ftpmodule=>array('host'=>'example.com','user'=>'anon')
);
private $modules=array();
function init(){
$interface=new reflectionclass('module');
foreach($this->configdata as $modulename=>$params){
$module_class=new reflectionclass($modulename);//根据配置configdata的名称,实例化reflectionclass
if(!$module_class->issubclassof($interface)){//检查反射得到了类是否是$interface的子类
throw new exception(unknown module type:$modulename);//不是module子类则抛出异常
}
$module=$module_class->newinstance();//实例化一个ftpmodule或者personmodule对象
foreach($module_class->getmethods() as $method){//获得类中的方法
$this->handlemethod($module,$method,$params);
}
array_push($this->modules,$module);//将实例化的module对象放入$modules数组中
}
}
function handlemethod(module $module,reflectionmethod $method,$params){
$name=$method->getname();//获得方法名称
$args=$method->getparameters();//获得方法中的参数
if(count($args)!=1||substr($name,0,3)!=set){//检查方法必须是以set开头,且只有一个参数
return false;
}
$property=strtolower(substr($name,3));//讲方法名去掉set三个字母,作为参数
if(!isset($params[$property])){//如果$params数组不包含某个属性,就返回false
return false;
}
$arg_class=@$args[0]->getclass;//检查setter方法的第一个参数(且唯一)的数据类型
if(empty($arg_class)){
$method->invoke($module,$params[$property]);
}else{
$method->invoke($module,$arg_class->newinstance($params[$property]));
}
}
}
$test=new modulerunner();
$test->init();
?>
二 通过反射获得类中信息:
复制代码 代码如下:
getfilename();
$lines=@file($path);
$from=$class->getstartline();
$to=$class->getendline();
$len=$to-$from+1;
return implode(array_slice($lines,$from-1,$len));
}
}
$classname=person;
$path=../practice/{$classname}.php;
if(!file_exists($path)){
throw new exception(no such file as {$path});
}
require_once($path);
if(!class_exists($classname)){
throw new exception(no such class as {$classname});
}
print reflectionutil::getclasssource(new reflectionclass('person'));
?>
结果是:class person{ public $age; public $name; function getname(){return zjx;} function getage(){return 12;} function __tostring(){ $rs=$this->getname(); $rs.=(age.$this->getage().); return $rs; } }
http://www.bkjia.com/phpjc/327710.htmlwww.bkjia.comtruehttp://www.bkjia.com/phpjc/327710.htmltecharticle一 反射的使用: 复制代码 代码如下: ?php class person{ public $name; function __construct($name){ $this-name=$name; } } interface module{ function execute(); } class...