gpt4 book ai didi

PHP文件/类名冲突

转载 作者:行者123 更新时间:2023-12-04 16:54:00 26 4
gpt4 key购买 nike

我有这样的文件结构:

Class (folder):
- User.php
- Rule.php
Scripts (folder):
- user.php (in lowercase)
- otherscript.php

index.php

规则类(Class/Rule.php):
namespace My\Namespace;
require_once 'Gender.php';
require_once 'User.php';

class Rule
{
...

用户类(Class/User.php):
namespace My\Namespace;
require_once 'Gender.php';
class User {
...

在 Rule 类中,我使用了一个包含 User 类(require_once 'User.php')的“require_once”,问题是当我在“otherscript.php”中包含 de Rule 类时,它同时包含我两个(script/user.php和类/User.php)。我怎样才能避免这种情况?

最佳答案

您可以 require_once元素相对于自身而不是当前工作目录的任何内容:

   require_once __DIR__.'/Gender.php';
require_once __DIR__.'/User.php';

...但最好只定义一个自动加载器(使用 SPL 自动加载器而不是旧的 __autoload 函数),它会为您处理这些,消除对类的大多数包含/要求语句的需要。

关于PHP文件/类名冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11104615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com