PHP __autoload 无法重新声明
我开始使用 PHP __autoload 函数,现在我遇到了那些奇怪的 Fatal error: Cannot redeclare class xxx 错误。
这很奇怪,因为这些错误发生在我什至没有使用自动加载函数加载的类上。我还使用 require_once 来包含文件。
我对此真的很困惑。有人知道使用自动加载时出现这种错误吗?
I started to use the PHP __autoload function and now I'm getting those weird Fatal error: Cannot redeclare class xxx errors.
It's weird since these errors occur on classes I don't even load with the autoload function. And I also use require_once to include the files.
I'm really puzzled about this. Anyone knows anything about this kind of errors when using autoload?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我不是假装最佳答案。只是我的想法。
__autoload() 在 PHP 7.2 中已弃用,并且可能会被删除。
我找到了这种上传/包含文件的方法
I am not pretend on the best answer. Just my thoughts.
__autoload() is deprecated in PHP 7.2 and will be possiblly deleted.
I found this way to upload/include files
我以前也遇到过这种情况,但不知道是什么原因造成的。确保您使用的是
require_once
/include_once
而不是初学者的普通版本。我认为问题与使用class_exists
而不告诉它跳过自动加载有关 (class_exists($name, false)
) - 你在这样做吗?I've had this before, not sure what caused it though. Make sure you're using
require_once
/include_once
rather than the normal versions for starters. I think the problem was related to usingclass_exists
without telling it to skip autoloading (class_exists($name, false)
) - are you doing this?我发现了问题。显然,当它想要包含 Bank 类时,它从当前目录中获取了“bank.php”文件^^。这只是银行页面,它应该包含“src/model/Bank.php”。我从搜索列表中删除了当前目录,它已被修复。
因此,请始终确保自动加载功能包含正确的文件。好的做法是更直接地命名您的文件,例如 class.Bank.php 或 class.User.php,而不是 Bank.php 或 User.php。
无论如何,感谢您的帮助和快速回复!
I found the problem. Apparently when it wanted to include Bank class, it took the "bank.php" file from the current directory ^^. Which is just the bank page, it should have include "src/model/Bank.php". I removed the current directory from the search list and it has been fixed.
So always make sure the autoload function is including the correct files. Good practice is too name your files more straightforward like class.Bank.php or class.User.php instead of Bank.php or User.php.
Thanks for your help and quick response anyway!
我有同样的情况..我所做的一切改变是它对我
有用
i had same situation .. all i changed was and its working for me
to
require_once
/include_once
仅在尝试包含文件时查看文件名,而不是类名。因此,您可以在 Foo.php 和 B.php 中都有类Foo
,然后您就会收到该错误。我不确定
__autoload
会如何给您带来任何问题,除非__autoload
需要 Foo.php,因为它需要类Foo
,而您需要 B .php 手动重新定义类Foo
。顺便说一下,使用
spl_autoload_register
而不是__autoload
。require_once
/include_once
only looks at the file name when they're trying to include a file, not a class name. So you can have classFoo
in both Foo.php and B.php, and then you'll get that error.I'm not sure how
__autoload
would cause you any problems, unless__autoload
requires Foo.php because it needs classFoo
, and you require B.php manually which redefines classFoo
.By the way, use
spl_autoload_register
instead of__autoload
.