duanhuo3392 2013-09-12 15:21
浏览 71
已采纳

关于php中include_once的困惑

I have this:

class/
    |-- A.Class.php
    |-- FactoryA.php
    |-- Database.php
    |-- Log.php
index.php

whereby FactoryA.php is a Factory class that creates obj A and can create/read/update/delete A from database. Log.php is a class that send logs to a text file log.txt.

FactoryA will require A.Class (to create the instance) and Database. All 3 classes requires Log.php (for debugging purpose). All index.php does is to create a FactoryA instance.

I don't know where I should place include statements. Do I include all files from index.php? Or do I do it in class?

  • 写回答

3条回答 默认 最新

  • ds9567 2013-09-12 15:28
    关注

    If you do not use an autoloader (see Autoloading CLasses), you will have to manually include all necessary files in all dependent files. It is typically recommended that all files manage all of their own dependencies.

    If I understand your dependencies, this would look like:

    • Index.php will need to require_once FactoryA.php
    • FactoryA.php will require_once A.Class.php & Log.php
    • A.Class.php will require_once Database.php & Log.php
    • Database.php will require_once Log.php

    An alternative method would be to use __autoload and let it fetch the needed files, as needed, for you. Thus, in your

    function __autoload($class_name) {
        include './class/' . $class_name . '.php';
    }
    $a = new A();
    

    However, spl_autoload_register() provides a more flexible alternative for autoloading classes. For this reason, using __autoload() is discouraged and may be deprecated or removed in the future. See the PHP Ref.

    We suggest you check out the PSR-0 standard and you can probably just use the SplClassLoader.php gist.

    You will need to rename your classes to follow namespace and path standards, but then you can just do something like:

    //This is the only file you need to require
    require_once('/path/to/SplClassLoader.php');
    $classLoader = new SplClassLoader('Class', './class');
    $classLoader->register();
    $a = new A();
    

    I have written a small CLI reference project to demonstrate, checkout bubba-h57/AutoLoading and run it from the command line. You should see results like:

    [cinamon-vm] AutoLoading> php index.php 
    From the factory!
    From the AClass!
    From the Database!
    Pure win!
    

    See Why doesn't PHP's Autoload feature work in CLI mode? for a discussion on using the autoloader from command line (cli) scripts.

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

报告相同问题?

悬赏问题

  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?
  • ¥100 求三轴之间相互配合画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败