关于一个简单的 PHP 自动加载器的问题

发布于 2024-09-11 06:56:55 字数 761 浏览 2 评论 0原文

我刚刚学习 PHP 命名空间并开始创建一个简单的自动加载函数。 O 所做的是:

function __autoload($name) {
  echo $name . "<br />";
  require_once $name . ".php";
}

所以,如果我不使用任何别名或导入语句,例如,这将有效。 使用 MainNamespace\Subnamespace 因为如果我这样做,假设我有:

\GreatApp\Models\User.php
\GreatApp\Models\Project.php
\GreatApp\Util\Util.php
\GreatApp\Util\Test\Test.php

如果我尝试这样做:

new GreatApp\Models\User();

它会起作用,因为自动加载中的 $name 将变成 GreatApp\Models\ User,因此找到 GreatApp\Models\User.php。但是当我这样做时:

use GreatApp\Models;
new User();

它失败了,因为现在 $name 只是 User 并且将找不到 User.php 。那我应该如何设置自动加载呢?

I was just learning aboutt PHP namespaces and starting to create a simple autoload function. What O did was:

function __autoload($name) {
  echo $name . "<br />";
  require_once $name . ".php";
}

So, this works if I do not use any aliasing or importing statements eg. use MainNamespace\Subnamespace because if I did that, assuming i have:

\GreatApp\Models\User.php
\GreatApp\Models\Project.php
\GreatApp\Util\Util.php
\GreatApp\Util\Test\Test.php

if I try to do:

new GreatApp\Models\User();

it works because $name in autoload will become GreatApp\Models\User so GreatApp\Models\User.php is found. But when I do:

use GreatApp\Models;
new User();

it fails because now $name is just User and User.php will not be found. How should I setup autoloading then?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

安稳善良 2024-09-18 06:56:55

无论您如何导入命名空间并引用类,完整的命名空间路径始终会传递到自动加载器。它应该有效。

只有 __autoload 函数本身应该属于主(根)命名空间

Full namespace path is always passed to the autoloader no matter how you import namespace and reference a class. It should work.

Just the __autoload function itself should belong to main (root) namespace

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文