Reputation:
I'm building a namespace which uses the same class name as a class that I'm including into the namespace.
require_once 'MyClass.php'; // already declares a class MyClass
namespace foo;
class MyClass {}
class MySubClass extends MyClass {}
How exactly would I do this without getting a "you cannot redeclare class..."?
Upvotes: 3
Views: 485
Reputation: 173522
First of all, the namespace declaration must be the first statement; and when you do this, it will just work:
namespace foo;
require_once 'MyClass.php'; // already declares a class MyClass
class MyClass {}
class MySubClass extends MyClass {}
Now, \MyClass
refers to the class you have declared in MyClass.php
(assuming it was declared without a specific namespace) whereas MyClass
refers to the one inside the current namespace.
Alternatively, you can alias it:
namespace foo;
use MyClass as StdMyClass;
require_once 'MyClass.php'; // already declares a class MyClass
class MyClass {}
class MySubClass extends MyClass {}
In this case StdMyClass
can be seen as an alias of \MyClass
.
Upvotes: 1