加载所有类,然后执行所有现有的{classname}::__initiation();


Load all classes and after that execute all existing {classname}::__initiation();

我想做标题中的内容。例如,我将所有文件都包含在我的类中:

foreach(glob("library/*.php") as $file)
    include $file;

在那之后,我定义了我所有的类。其中一些具有静态函数,例如__initiation。包含后如何执行所有这些?类似于这里:

foreach( {classes} as $class ){
    if( function_exists( $class . '::__initiation' ) )
        $class::__initiation();
}

我想这么做是因为有些类必须准备好(例如数据库连接),而有些类必须使用其他类。通常,在两个方向上(名为foo的类必须用于初始化名为barar的类则必须使用名为foo>的类别)。有人知道怎么做吗

示例:

class database{
    // some stuff
    public static __initiation(){
        database::connect();
        foo::bar();
    }
}
class foo{
    // some stuff
    public static bar(){/* blah blah blah */}
    public static __initiation(){
        database::select(/* blah blah blah */);
        foo::start();
    }
}
// Execute all declared {classname}::__initiation() function right now.

提前感谢您的帮助。

您将遇到的主要问题是文件按字母顺序排列。但是它们之间的依赖关系不是按这个顺序排列的,例如bar引用foo,当bar加载时,foo还没有加载。

你知道__自动加载功能吗?这是我的AutoLoader类,它可以帮助你:

<?php
namespace de'g667'util;
class AutoLoader
{
    /**
     * Registers the autoload-function. All needed classes and interfaces will be
     * automatically loaded on demand.
     */
    static function register() {
        spl_autoload_register(
        function ($class) {
            $class = str_replace ("''", "/", $class);
            $cwd = getcwd();
            $filepath = $class.'.php';
            $path = PATH . DIRECTORY_SEPARATOR . $filepath;
            if( ! file_exists($path) ){
                error_log("Autoloading $class failed");
            }
            require_once $path;
        }
        );
    }
    static function setPath($path) {
        define("PATH", $path);
    }
}
?>

将此代码保存在/library/de/g667/AutoLoader.php 中

自动加载器的使用:

  <?php
  require_once 'library/de/g667/util/AutoLoader.php';
  use de'g667'util'AutoLoader;
  AutoLoader::setPath("/path/to/library");
  AutoLoader::register();
  ?>

请注意,库文件夹中的每个类都有一个文件。在AutoLoader中插入您的实例化函数,然后您应该能够轻松地实例化类。