0

我正在尝试摆脱以下自定义函数中的全局变量。它的作用是注册类目录中文件中自动定义的类,并将它们重新定义为具有指定后缀的扩展类。

autoload_classes();
print_r(get_declared_classes());   

function autoload_classes() {
    global $class_files, $dirpath;
    $dirpath = dirname(__FILE__) . '/classes/';
    $class_files = array_map(create_function( '$a', 'return basename($a, ".php");' ), glob($dirpath . '*.php'));
    spl_autoload_register(
        create_function('$class_name', '
            global $class_files, $dirpath;
            if (in_array($class_name, $class_files)) 
                include($dirpath . $class_name . ".php");' )
    );

    foreach ($class_files as $class_name) {
        $class_name_alpha = $class_name . "_alpha";
        eval("class $class_name_alpha extends $class_name {};");    
    }
}

我试过这样,但它会导致错误。我该如何解决?

autoload_classes();
print_r(get_declared_classes());   

function autoload_classes() {

    $dirpath = dirname(__FILE__) . '/classes/';
    $class_files = array_map(create_function( '$a', 'return basename($a, ".php");' ), glob($dirpath . '*.php'));
    spl_autoload_register(
        create_function('$class_name', '        
            if (in_array($class_name, ' . var_export($class_files, true) . ')) 
                include(' . $dirpath . ' . $class_name . ".php");
        ')
    );

    foreach ($class_files as $class_name) {
        $class_name_alpha = $class_name . "_alpha";
        eval("class $class_name_alpha extends $class_name {};");    
    }
}

我的一些服务器低于 PHP v5.3,所以不能使用闭包。感谢您的信息。

4

1 回答 1

0

好的,这行得通。我认为var_export()仅对数组是必需的,但包含字符串的变量也需要它。

autoload_classes();
print_r(get_declared_classes());   

function autoload_classes() {

    $dirpath = dirname(__FILE__) . '/classes/';
    $class_files = array_map(create_function( '$a', 'return basename($a, ".php");' ), glob($dirpath . '*.php'));
    spl_autoload_register(
        create_function('$class_name', '        
            if (in_array($class_name, ' . var_export($class_files, true) . ')) 
                include(' . var_export($dirpath, true) . ' . $class_name . ".php");
        ')
    );

    foreach ($class_files as $class_name) {
        $class_name_alpha = $class_name . "_alpha";
        eval("class $class_name_alpha extends $class_name {};");    
    }
}
于 2012-09-20T12:28:53.560 回答