抱歉,评论被关闭
魔术和反射机制节约代码
在弄数据映射的时候发觉有更加简单的代替原来那种方法!
主要用到了PHP本身的魔术及反射机制,哈哈可以节约代码!
User手工创建getter,setter
UserRe是自动创建
他们两个完成的功能是一样的!
reflecttest.php 源码所示如下:
<?php
/**
* author:凹凸曼
* email:jar-c@163.com
*/
class User{
protected $id;
protected $name='';
protected $tel='';
public function __construct(){
}
public function setName($name){
$this->name=$name;
}
public function getName(){
return $this->name;
}
public function setTel($tel){
$this->tel=$tel;
}
public function getTel(){
return $this->name;
}
public function setId($id){
$this->id=$id;
}
public function getId(){
return $this->id;
}
}
class UserRe{
protected $id;
protected $name='';
protected $tel='';
public function __construct(){
}
public function __call($name,$args){
if(preg_match('/^(set|get)(\w+)/',$name,$matches)){
$ckeys=array_keys(get_class_vars(get_class($this)));
foreach($ckeys as $v){
$temp[]=ucwords($v);
}
if('get'==$matches[1]){
if(in_array($matches[2],$temp)){
return $this->adttribute;
}
}else{
$this->adttribute=$args[0];
}
}
}
}
/******测试区域*********/
$ur1 =new User();
$ur1->setName("User:aotuman 1 ");
echo $ur1->getName();
$ur =new UserRe();
$ur->setName("UserRe:aotuman 2");
echo $ur->getName();
?>
本文出自 “凹凸曼” 博客,请务必保留此出处 http://www.apoyl.com/?p=653
日志信息 »
该日志于2011-04-29 01:53由 凹凸曼 发表在PHP分类下,
评论已关闭。
目前盖楼
« PHP__魔术方法简介
一道灵异的程序试题 »

