PHP手册-__NAMESPACE__关键字(命名空间中继承其他命名空间中类注意)

常量__ 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) 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值