【问题标题】:Autoload imported namespaces in PHP在 PHP 中自动加载导入的命名空间
【发布时间】:2014-05-01 11:08:23
【问题描述】:

The question asked here is very similar.

我正在尝试编写一个自动加载器来支持导入的命名空间。我的目录结构如下(列出了类文件):

/includes
     /php
         config.php
         Shapes.php
         Animals.php
/PetsModule
     /classes
         Cat.php
         Dog.php
     pcontroller1.php
     pcontroller2.php
/MathModule
     /classes
         Triangle.php
         Square.php
     mcontroller1.php
     mcontroller2.php

我所有的控制器都包含 config.php 文件,其中包含我的自动加载器代码:

<?php

spl_autoload_register(function($fqClassName) {
    $fqClassName = ltrim($fqClassName, '\\');
    $lastSlash = strrpos($fqClassName, '\\');

    if($lastSlash) {
        // The class is in a namespace
        require '/' . str_replace('\\', '/', substr($fqClassName, 0, $lastSlash)) . '/classes/' . substr($fqClassName, $lastSlash + 1) . '.php';
    } else {
        // The class is global
        require "/includes/php/$fqClassName.php";
    }
}, true);

现在这适用于所有基本情况,但是当您开始导入命名空间时它会失败。例如:

<?php

namespace MathModule;

use PetsModule;

$t = new Triangle(60, 60, 60); // works fine
$fluffy = new Cat("Fluffy"); // fails

传递给自动加载器函数的完全限定类名是MathModule\Cat,这是一个合理的假设。

有没有办法让自动加载器与导入的命名空间一起工作?我猜肯定有办法,因为我的自动加载器与 PSR-0 的自动加载器非常相似。

【问题讨论】:

    标签: php namespaces autoload spl-autoload-register


    【解决方案1】:

    自动加载无关紧要。

    要使用new Cat("Fluffy"),你应该写use PetsModule\Cat;use PetsModule\Cat as Cat;

    http://www.php.net/manual/en/language.namespaces.importing.php

    【讨论】:

      猜你喜欢
      • 2013-11-25
      • 2014-04-13
      • 2011-04-08
      • 2011-08-06
      • 2015-07-15
      • 2012-05-21
      相关资源
      最近更新 更多