douyu1656 2011-03-12 03:26
浏览 17
已采纳

来自不同文件夹的自动加载类

This is how I autoload all the classes in my controllers folder,

# auto load controller classes
    function __autoload($class_name) 
    {
        $filename = 'class_'.strtolower($class_name).'.php';
        $file = AP_SITE.'controllers/'.$filename;

        if (file_exists($file) == false)
        {
            return false;
        }
        include ($file);
    }

But I have classes in models folder as well and I want to autoload them too - what should I do? Should I duplicate the autoload above and just change the path to models/ (but isn't this repetitive??)?

Thanks.

EDIT:

these are my classes file names in the controller folder:

class_controller_base.php
class_factory.php
etc

these are my classes file names in the model folder:

class_model_page.php
class_model_parent.php
etc

this is how I name my controller classes class usually (I use underscores and lowcaps),

class controller_base 
{
...
}

class controller_factory
{
...
}

this is how I name my model classes class usually (I use underscores and lowcaps),

class model_page 
    {
    ...
    }

    class model_parent
    {
    ...
    }
  • 写回答

12条回答 默认 最新

  • doulongti5932 2011-03-12 03:28
    关注

    You should name your classes so the underscore (_) translates to the directory separator (/). A few PHP frameworks do this, such as Zend and Kohana.

    So, you name your class Model_Article and place the file in classes/model/article.php and then your autoload does...

    function __autoload($class_name) 
    {
        $filename = str_replace('_', DIRECTORY_SEPARATOR, strtolower($class_name)).'.php';
    
        $file = AP_SITE.$filename;
    
        if ( ! file_exists($file))
        {
            return FALSE;
        }
        include $file;
    }
    

    Also note you can use spl_autoload_register() to make any function an autoloading function. It is also more flexible, allowing you to define multiple autoload type functions.

    If there must be multiple autoload functions, spl_autoload_register() allows for this. It effectively creates a queue of autoload functions, and runs through each of them in the order they are defined. By contrast, __autoload() may only be defined once.

    Edit

    Note : __autoload has been DEPRECATED as of PHP 7.2.0. Relying on this feature is highly discouraged. Please refer to PHP documentation for more details. http://php.net/manual/en/function.autoload.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(11条)

报告相同问题?

悬赏问题

  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿