如何在自动加载中使用 PHP 命名空间? [英] How do I use PHP namespaces with autoload?

查看:27
本文介绍了如何在自动加载中使用 PHP 命名空间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I get this error when I try to use autoload and namespaces:

致命错误:/usr/local/www/apache22/data/public/php5.3/test.php 中找不到类Class1">第 10 行

Fatal error: Class 'Class1' not found in /usr/local/www/apache22/data/public/php5.3/test.php on line 10

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

Can anyone tell me what I am doing wrong?

这是我的代码:

Class1.php:

Class1.php:

<?php

namespace PersonBarnesDavid
{
    class Class1
    {
        public function __construct()
        {
            echo __CLASS__;
        }
    }
}

?>

test.php:

<?php

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

use PersonBarnesDavid;

$class = new Class1();

?>

推荐答案

Class1 不在全局范围内.

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

Note that this is an old answer and things have changed since the days where you couldn't assume the support for spl_autoload_register() which was introduced in PHP 5.1 (now many years ago!).

现在,您可能会使用 Composer.在幕后,这将是这个片段的内容,以启用 类自动加载.

These days, you would likely be using Composer. Under the hood, this would be something along the lines of this snippet to enable class autoloading.

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

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

For completeness, here is the old answer:

要加载未在全局范围内定义的类,您需要使用自动加载器.

To load a class that is not defined in the global scope, you need to use an autoloader.

<?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 PersonBarnesDavid as MyPerson;

$class = new MyPersonClass1();

或不带别名:

use PersonBarnesDavidClass1;

$class = new Class1();

这篇关于如何在自动加载中使用 PHP 命名空间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆