Php ';未找到类';即使文件被正确地包括在内

Php ';未找到类';即使文件被正确地包括在内,php,class,namespaces,include,Php,Class,Namespaces,Include,因此,我有一组非常简单的文件: main.php include_once 'User.php'; echo 'im here'; //never reached! $user = new My\Test\User(); ... User.php namespace My\Test; include_once 'Student.php'; class User {...} Student.php namespace My\Test; include_once 'User.php'

因此,我有一组非常简单的文件:

main.php

include_once 'User.php';

echo 'im here'; //never reached!

$user = new My\Test\User();

...
User.php

namespace My\Test;

include_once 'Student.php';

class User {...}
Student.php

namespace My\Test;

include_once 'User.php';

var_dump(in_array('User.php', get_included_files())); //true

var_dump(class_exist('User')); //false
var_dump(class_exist('\My\Namespace\User')); //false
var_dump(class_exist('My\Namespace\User')); //false - How can that be?

class Student extends User {...} //Fatal Error: Class My\Namespace\User not found
因此,这里发生的事情是,User类首先包含在main.php中。因为它有一些创建学生实例的静态方法,所以它需要包含学生类文件。在扩展User时,Students文件也包含User.php,但不应该执行,因为我曾经使用过include_。我甚至检查了文件是否正确包含,但是几行之后我得到了致命错误。两个文件具有相同的命名空间

有趣的是,在我将名称空间应用到我的类之前,一切都正常,所以我假设这是一种交叉错误,包括具有相同名称空间的文件

尝试从Student.php中删除include_一次,没有任何区别

如果main.php包括User.php,User.php包括Student.php,为什么Student.php找不到用户类


我使用的是PHP版本5.5.9,在调用main.PHP创建新用户()时,它没有在正确的命名空间中运行

您需要在main.php中指定名称空间,或者使用正确的名称空间(我将名称空间命名为MyNamespace-因为您的伪代码的名称空间名称无效)


请参阅我的答案-您可能需要稍微编辑您的帖子,因为您在这里列出的示例名称空间是“名称空间”,它不是有效的名称空间名称。在我的回答中,我将您的名称空间更改为“MyNamespace”--但使用您在问题中遇到问题的实际名称空间将有助于确保答案符合您的需要。我的错,这只是为了演示。我在代码中检查了它,并使用了完整的名称空间名称。关键是,永远不会到达'im here'(因此new User()),致命错误会在Student.php中抛出……如果查看运行代码的输出,我会使用我在main.php中添加的名称空间得到“im here”。
<?php
namespace MyNamespace;

include_once 'User.php';

echo 'im here'; //never reached!

$user = new User();
Scotts-rMBP-3:bar smoore$ php main.php 
bool(false)
bool(false)
bool(true)
bool(true)
im here