繁体   English   中英

PHP __autoload 无法重新声明

[英]PHP __autoload Cannot redeclare

我开始使用 PHP __autoload function,现在我遇到了那些奇怪的致命错误:无法重新声明 class xxx 错误。

这很奇怪,因为这些错误发生在我什至不使用自动加载 function 加载的类上。 而且我还使用 require_once 来包含文件。

我真的很困惑。 使用自动加载时,任何人都知道这种错误吗?

require_once / include_once仅在尝试包含文件时查看文件名,而不是 class 名称。 所以你可以在 Foo.php 和 B.php 中都有 class Foo ,然后你会得到那个错误。

I'm not sure how __autoload would cause you any problems, unless __autoload requires Foo.php because it needs class Foo , and you require B.php manually which redefines class Foo .

顺便说一句,使用spl_autoload_register而不是__autoload

我有同样的情况..我改变的只是它对我有用

include('xxx.php');

require_once('xxx.php');

我不是假装最好的答案。 只是我的想法。

__autoload() 在 PHP 7.2 中已弃用,可能会被删除。

我找到了这种上传/包含文件的方法

//initialize a function which will upload files
function upload(){//you can call the function as you like
  //your path to files goes here
}

spl_autoload_register('upload')//specify the function, where you include your files(in this case it's upload function   

我以前也遇到过,不知道是什么原因造成的。 确保您使用的是require_once / include_once而不是初学者的普通版本。 我认为问题与使用class_exists并没有告诉它跳过自动加载( class_exists($name, false) )有关 - 你在这样做吗?

我发现了问题。 显然,当它想要包含 Bank class 时,它从当前目录中获取了“bank.php”文件^^。 这只是银行页面,它应该包含“src/model/Bank.php”。 我从搜索列表中删除了当前目录,它已被修复。

因此,请始终确保自动加载 function 包含正确的文件。 Good practice is too name your files more straightforward like class.Bank.php or class.User.php instead of Bank.php or User.php.

无论如何,感谢您的帮助和快速响应!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM