【问题标题】:get parent extends class in php在php中获取父类扩展类
【发布时间】:2012-01-06 22:13:37
【问题描述】:

我有 oop php 代码:

class a {
    // with properties and functions
}

class b extends a {
    public function test() {
        echo __CLASS__; // this is b
        // parent::__CLASS__ // error
    }
}

$b = new b();
$b->test();

我有一些父类(普通和抽象)和许多子类。子类扩展了父类。所以当我在某个时候实例化孩子时,我需要找出我调用的父母。

例如函数b::test()将返回a

我怎样才能(从我的代码)从我的 b 类获得 a 类?

谢谢

【问题讨论】:

标签: php class parent extend


【解决方案1】:

您的代码建议您使用parent,这实际上就是您所需要的。问题在于神奇的__CLASS__ 变量。

documentation 声明:

从 PHP 5 开始,该常量返回声明的类名。

这是我们需要的,但正如 php.net 上的this comment 所述:

claude 指出__CLASS__ 始终包含调用它的类,如果您希望调用该方法的类使用 get_class($this) 代替。然而,这只适用于实例,而不是静态调用时。

如果您只需要父类,那么也有一个功能。那个叫get_parent_class

【讨论】:

    【解决方案2】:

    你可以使用get_parent_class:

    class A {}
    class B extends A {
      public function test() {
        echo get_parent_class();
      }
    }
    
    $b = new B;
    $b->test(); // A
    

    如果B::test 是静态的,这也将起作用。

    注意:使用不带参数的 get_parent_class 与传递 $this 作为参数之间存在细微差别。如果我们扩展上面的例子:

    class C extends B {}
    
    $c = new C;
    $c->test(); // A
    

    我们得到A作为父类(B的父类,方法被调用的地方)。如果您总是想要您正在测试的对象的最接近的父对象,您应该改用get_parent_class($this)

    【讨论】:

      【解决方案3】:
      class a {
        // with propertie and functions
      }
      
      class b extends a {
      
         public function test() {
            echo get_parent_class($this);
         }
      }
      
      
      $b = new b();
      $b->test();
      

      【讨论】:

        【解决方案4】:

        您可以使用反射来做到这一点:

        代替

        parent::__CLASS__;
        

        使用

        $ref = new ReflectionClass($this);
        echo $ref->getParentClass()->getName();
        

        【讨论】:

          【解决方案5】:

          请改用class_parents。它会给出一组父母。

          <?php
          class A {}
          class B extends A {
          }
          class C extends B {
              public function test() {
                  echo implode(class_parents(__CLASS__),' -> ');
              }
          }
          
          $c = new C;
          $c->test(); // B -> A
          

          【讨论】:

            猜你喜欢
            • 2016-11-09
            • 2019-07-04
            • 1970-01-01
            • 1970-01-01
            • 2011-10-31
            • 2019-08-11
            • 1970-01-01
            • 2015-08-20
            • 2015-11-03
            相关资源
            最近更新 更多