2008年11月6日星期四

php中访问对象protected成员的一种方法

/**
* ZxProtectedAccessor
*
* ZxProtectedAccessor 提供了访问对象protected属性的途径。
*
* @copyright Copyright Zhenye Xie 2006. All rights reserved.
* @author Zhenye Xie
* @version 0.8
* @package common
*/
class ZxProtectedAccessor {
private static $classes=array();

private static function generateAccessor($class){
$accClass=self::getAccessorClassName($class);
if(!class_exists($accClass)){
$code='class '.$accClass.' extends '.$class.' { ';
$code.='static function &_zx_get_var_($obj,$var){return $obj->$var;}';
$code.='static function _zx_set_var_($obj,$var,$value){$obj->$var=$value;}}';
eval($code);
}
}

function &get($object, $var){
$class=get_class($object);
self::generateAccessor($class);
$ret=call_user_func(array(self::getAccessorClassName($class),
'_zx_get_var_'),$object,$var);
return $ret;
}

function set($object, $var, $value){
$class=get_class($object);
self::generateAccessor($class);
$ret=call_user_func(array(self::getAccessorClassName($class),
'_zx_set_var_'),$object,$var,$value);
return $ret;
}

private static function getAccessorClassName($className){
return '_Zx_Protected_Accessor__'.$className;
}
}

没有评论:

发表评论

网站统计