'Class not found' even though file is properly included

So I have a really simple set of files:



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


So what happens here is that the User class is included first from main.php. Because it has some static methods that create Students instances aswell it needs to include the Students class file. The Students file, as it extends User, includes User.php aswell, but that should not be executed, since I used include_once. I even check if the file was included properly, yet a few lines later I get the fatal error. Both files have the same namespace.



Whats funny is that before I applied namespaces to my classes everything worked, so I assume it is some kind of bug with cross-including files with the same namespace.



Tried to remove the include_once from Student.php, it makes no difference.



If main.php includes User.php, and User.php includes Student.php, why cant Student.php not find the User class?!



I'm on PHP Version 5.5.9



Answers

Your main.php is not operating within the correct namespace, when it is calling to create a new User();.



You need to specify the namespace in main.php, or otherwise use the correct namespace (I named the namespace MyNamespace - since your pseudo code had an invalid namespace name of Namespace).



<?php
namespace MyNamespace;

include_once 'User.php';

echo 'im here'; //never reached!

$user = new User();


Once you change to this you get:



Scotts-rMBP-3:bar smoore$ php main.php 
bool(false)
bool(false)
bool(true)
bool(true)
im here