如何将 PHP 命名空间与自动加载结合使用?

2022-08-30 07:28:37

当我尝试使用自动加载和命名空间时,我收到此错误:

致命错误:类“Class1”在第 10 行/usr/local/www/apache22/data/public/php5.3/test.php

谁能告诉我我做错了什么?

这是我的代码:

第1类.php:

<?php

namespace Person\Barnes\David
{
    class Class1
    {
        public function __construct()
        {
            echo __CLASS__;
        }
    }
}

?>

测试.php:

<?php

function __autoload($class)
{
    require $class . '.php';
}

use Person\Barnes\David;

$class = new Class1();

?>

答案 1

Class1不在全局范围内。

请注意,这是一个古老的答案,自从您无法假设在PHP 5.1中引入了对它的支持以来,事情已经发生了变化(现在是很多年前!spl_autoload_register()

如今,您可能会使用Composer。在引擎盖下,这将是与此代码段类似的内容,以启用类自动加载

spl_autoload_register(function ($class) {
    // Adapt this depending on your directory structure
    $parts = explode('\\', $class);
    include end($parts) . '.php';
});

为了完整起见,这是旧的答案:

若要装入未在全局作用域中定义的类,需要使用自动装入器。

<?php

// Note that `__autoload()` is removed as of PHP 8 in favour of 
// `spl_autoload_register()`, see above
function __autoload($class)
{
    // Adapt this depending on your directory structure
    $parts = explode('\\', $class);
    require end($parts) . '.php';
}

use Person\Barnes\David as MyPerson;

$class = new MyPerson\Class1();

或不带别名:

use Person\Barnes\David\Class1;

$class = new Class1();

答案 2

如前所述,Pascal MARTIN,您应该将“\”替换为DIRECTORY_SEPARATOR例如:

$filename = BASE_PATH . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
include($filename);

另外,我建议您重新组织dirrectory结构,以使代码更具可读性。这可能是一种替代方案:

目录结构:

ProjectRoot
 |- lib

文件:/ProjectRoot/lib/Person/Barnes/David/Class1.php

<?php
namespace Person\Barnes\David
class Class1
{
    public function __construct()
    {
        echo __CLASS__;
    }
}
?>
  • 为定义的每个命名空间创建子目录。

文件:/ProjectRoot/test.php

define('BASE_PATH', realpath(dirname(__FILE__)));
function my_autoloader($class)
{
    $filename = BASE_PATH . '/lib/' . str_replace('\\', '/', $class) . '.php';
    include($filename);
}
spl_autoload_register('my_autoloader');

use Person\Barnes\David as MyPerson;
$class = new MyPerson\Class1();
  • 我使用php 5推荐用于自动加载器声明。如果您仍在使用 PHP 4,请将其替换为旧语法:函数 __autoload($class)

推荐