【问题标题】:Autoloading classes with namespaces and directories on Linux在 Linux 上使用命名空间和目录自动加载类
【发布时间】:2018-05-01 04:30:29
【问题描述】:

嘿,我只是在学习命名空间和自动加载的工作原理。似乎无法让它工作可以使用一些帮助。我使用codeigniter,相关的目录结构是这样的:

root/
    application/
        classes/
            testa/
                TestClass.php
            testb/
                UserClass.php
    html/
        index.php

TestClass.php的内容是

namespace application\classes\testa;

class TestClass {
    public $var = 'a default value';
    public function displayVar() {
        echo $this->var;
    }
}

我尝试以这样的方式自动加载内容,它可以与 index.php 中的 classes 文件夹中的任何目录结构一起使用(我在网上找到了这段代码)

// autoload classes based on a 1:1 mapping from namespace to directory 
// structure.
spl_autoload_register(function ($className) {
    # Usually I would just concatenate directly to $file variable 
    # below
    # this is just for easy viewing on Stack Overflow)

    $ds = DIRECTORY_SEPARATOR;
    $dir = __DIR__;

    // replace namespace separator with directory separator (prolly
    // not required)
    $className = str_replace('\\', $ds, $className);

    // get full name of file containing the required class
    $file = "{$dir}{$ds}{$className}.php";

    // get file if it is readable
    if (is_readable($file)) require_once $file;
});

但是当我尝试在 codeigniter 视图中实例化一个类时

$obj = new application\classes\testa\TestClass();

我明白了

An uncaught Exception was encountered
Type: Error
Message: Class 'application\classes\testa\TestClass' not found

我做错了什么?我以前从未真正使用过命名空间或类,所以我有点迷路了。我认为自动加载器写错了(也许它是用于 Windows 机器的?)但我不确定。感谢您的帮助。

【问题讨论】:

  • 这是您构建错误的路径。 index.php 中的$dir = __DIR__; 表示目录 html/ 。您无法在 html/ 下找到您的课程。尝试在屏幕上打印$file,看看您的文件路径是否正确。

标签: php class namespaces


【解决方案1】:

由于您在 Windows 机器上运行,我假设 root 在 C: 下:

在 index.php 中,$file = "{$dir}{$ds}{$className}.php"; 将是

C:\root\html\application\classes\testa\TestClass.php

你在那里找不到你的 TestClass.php。

正确的文件路径应该是

$file = "{$dir}{$ds}..{$ds}{$className}.php";

这将是

C:\root\html\..\application\classes\testa\TestClass.php

..\ 表示父目录。

【讨论】:

    【解决方案2】:

    感谢您的帮助。我设法弄清楚了。我为自动加载器使用了这个,它为类目录提供了正确的路径

    spl_autoload_register(function ($className) {
        // $ds = '/';
        $ds = DIRECTORY_SEPARATOR;
        // $dir = the path to this file (index.php), it always gives 
        // path to the current file
        $dir = __DIR__ ;
        // replace namespace separator with directory separator (prolly
        // not required)
        $className = str_replace('\\', $ds, $className);
        // get full name of file containing the required class 
        $file = '../' . $className . ".php";
        // get file if it is readable
        if (is_readable($file)) require_once $file;
    });
    

    顺便说一句,我使用的是 Linux,而不是 Windows

    【讨论】:

      猜你喜欢
      • 2014-11-02
      • 2013-06-29
      • 2011-11-19
      • 2013-11-30
      • 1970-01-01
      • 1970-01-01
      • 2017-11-03
      • 2021-06-29
      相关资源
      最近更新 更多