dpik71879
dpik71879
2012-04-24 10:25

php从类文件列表中创建对象

已采纳

I have directory CLASSES with files in my project.

../classes/class.system.php
../classes/class.database.php
...

I pull out every class and include it to main index.php with this code:

// load classes
foreach (glob("classes/class.*.php") as $filename) {
    require_once $filename;
}

and then I create (manually write) objects for example:

$system = new System();
$database = new Database();
...

Q: How can I automatically generate object for each class from list of files in directory CLASSES without writing them?

Thank you for your answers and code.

EDIT:

My working solution:

// load classes
foreach (glob("classes/class.*.php") as $filename) {
    require_once $filename;
    $t = explode(".",$filename);
    $obj = strtolower($t[1]);
    $class = ucfirst($t[1]);
    ${$obj} = new $class();
}
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

3条回答

  • doushi7761 doushi7761 9年前
    // load classes and create objects
    foreach (glob("classes/class.*.php") as $filename) {
        require_once $filename;
        $t = explode(".",$filename);
        $obj = strtolower($t[1]);
        $class = ucfirst($t[1]);
        // create object for every class
        ${$obj} = new $class();
    }
    
    点赞 评论 复制链接分享
  • dousi6303 dousi6303 9年前

    I don't think loading all classes with glob and including them if you need or not is efficient or good idea performance wise. What if you have 500 different classes ???

    Why don't you take advantage of PHP auto loading see http://php.net/manual/en/language.oop5.autoload.php which would only load the class you need

    Example

    function __autoload($className) {
        require_once "classes/class." . $className . ".php";
    }
    
    $system = new System();
    $database = new Database();
    
    点赞 评论 复制链接分享
  • douguo6472 douguo6472 9年前

    IF you follow a typical pattern, while creating those files like

    class.<classname>.php

    Then

    foreach (glob("classes/class.*.php") as $filename) {
        require_once $filename;
        $t = explode(".",$filename);
        ${strtolower($t[1])}= new ucfirst($t[1])(); // automatically create the object        
    
    }
    
    点赞 评论 复制链接分享

相关推荐