PHP手册-__NAMESPACE__关键字(命名空间中继承其他命名空间中类注意)
2012-08-05 16:53
344 查看
常量__ NAMESPACE__的值是包含当前命名空间名称的字符串。在全局的,不包括在任何命名空间中的代码,它包含一个空的字符串。
When extending a class from another namespace that should instantiate a class from within the current namespace, you need to pass on the namespace. <?php // File1.php namespace foo; class A { public function factory() { return new C; } } class C { public function tell() { echo "foo"; } } ?> <?php // File2.php namespace bar; class B extends \foo\A {} class C { public function tell() { echo "bar"; } } ?> <?php include "File1.php"; include "File2.php"; $b = new bar\B; $c = $b->factory(); $c->tell(); // "foo" but you want "bar" ?> You need to do it like this: When extending a class from another namespace that should instantiate a class from within the current namespace, you need to pass on the namespace. <?php // File1.php namespace foo; class A { protected $namespace = __NAMESPACE__;//此处是重点1,这样可以指定到当前命名空间中的对应类 public function factory() { $c = $this->namespace . '\C';//此处是重点2,这样可以指定到当前命名空间中的对应类 return new $c; } } class C { public function tell() { echo "foo"; } } ?> <?php // File2.php namespace bar; class B extends \foo\A { protected $namespace = __NAMESPACE__; } class C { public function tell() { echo "bar"; } } ?> <?php include "File1.php"; include "File2.php"; $b = new bar\B; $c = $b->factory(); $c->tell(); // "bar" ?> (it seems that the namespace-backslashes are stripped from the source code in the preview, maybe it works in the main view. If not: fooA was written as \foo\A and barB as bar\B)
相关文章推荐
- PHP基础之命名空间5——namespace关键字和__NAMESPACE__常量
- PHP命名空间 namespace 及导入 use 的用法
- PHP命名空间(Namespace)的使用详解
- PHP命名空间(Namespace)的使用详解
- PHP命名空间(Namespace)的使用详解
- php - 命名空间(namespace)
- PHP命名空间(Namespace)的使用详解
- PHP命名空间(Namespace)的使用详解
- php namespace use 命名空间
- Spring 使用其他命名空间的时候要注意的事项
- PHP命名空间(Namespace)的使用详解
- PHP命名空间 namespace 和 自动加载
- PHP命名空间(Namespace)的使用详解
- PHP命名空间(Namespace)的使用详解
- php 的 namespace(命名空间)的用法及说明
- PHP中命名空间的创建-使用namespace
- PHP命名空间(Namespace)的使用详解
- PHP命名空间(Namespace)的使用详解
- PHP命名空间namespace及use的简单用法分析
- 引用其他项目的类文件一定要注意这个类所在的命名空间