Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extending a class with an other namespace with the same ClassName

Tags:

namespaces

php

I'm trying to use namespaces. I want to extend a class inside a different namespace. The name of the class is the same. Example:

Parent:

namespace Base;  class Section extends Skeleton {  protected $id;  protected $title;  protected $stylesheet; } 

Child:

namespace Base2; use \Base\Section;  class Section      extends \Base\Section {  } 

It is an application which uses Doctrine 2 and Zend Framework. The Skeleton class used by Base/Section is just an abstract class that contains the magic methods (__get, _set, etc).

When I try to instantiate a \Base2\Section class it throws an error:

Fatal error: Cannot declare class Base2\Section because the name is  already in use in /var/www/test/application/Models/Base2/Section.php  on line 7 

Any idea's?

like image 947
Rene Terstegen Avatar asked Aug 10 '10 12:08

Rene Terstegen


People also ask

Can I have class with same name as namespace?

Inside a namespace, no two classes can have the same name.

Can we declare multiple namespaces in same file?

Multiple namespaces may also be declared in the same file. There are two allowed syntaxes. This syntax is not recommended for combining namespaces into a single file. Instead it is recommended to use the alternate bracketed syntax.

Can namespace and class have same name C++?

Well, a class name can be the same, but only when defined in different namespace.

What is alias in php?

The class_alias() function is an inbuilt function in PHP which is used to create an alias name of the class. The functionality of the aliased class is similar to the original class.


2 Answers

Just use fully qualified name

namespace Base2;  class Section      extends \Base\Section { } 

Or aliasing

namespace Base2; use \Base\Section as BSection;  class Section      extends BSection { } 
like image 196
Mchl Avatar answered Sep 24 '22 01:09

Mchl


when you say

use \Base\Section 

you are pulling the Section class into your current scope, causing a conflict when you want to create a new class called Section. just omit the use statement.

like image 30
Scott M. Avatar answered Sep 24 '22 01:09

Scott M.