php 使用具有相同 ClassName 的其他命名空间扩展类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3449122/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extending a class with an other namespace with the same ClassName
提问by Rene Terstegen
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).
它是一个使用 Doctrine 2 和 Zend Framework 的应用程序。Base/Section 使用的 Skeleton 类只是一个包含魔法方法(__get、_set 等)的抽象类。
When I try to instantiate a \Base2\Section class it throws an error:
当我尝试实例化 \Base2\Section 类时,它会引发错误:
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?
有任何想法吗?
回答by Mchl
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 {
}
回答by Scott M.
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.
您正在将 Section 类拉入当前范围,当您想要创建一个名为 Section 的新类时会导致冲突。只需省略 use 语句。