访问对象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;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.