【问题标题】:How can I get name of interface from abstract class in PHP如何从 PHP 中的抽象类中获取接口名称
【发布时间】:2014-02-28 08:46:56
【问题描述】:

在 php 中是否可以在不创建新对象的情况下获取接口名称?例如:

interface my_interface{}

abstract class foo implements my_interface{

      public static function get_interface(){
             // here return name of interface
      }

}

class bar extends foo{}

echo bar::get_interface();

预期输出:

 my_interface

【问题讨论】:

    标签: php function oop interface abstract-class


    【解决方案1】:

    利用Reflection

    $rc1 = new ReflectionClass("foo");
    echo $rc1->getInterfaceNames()[0];
    

    代码..

    <?php
    interface my_interface{}
    
    abstract class foo implements my_interface{
    
        public static function get_interface(){
            // here return name of interface
        }
    
    }
    
    $rc1 = new ReflectionClass("foo");
    echo $rc1->getInterfaceNames()[0];
    

    OUTPUT :

    my_interface
    

    【讨论】:

      【解决方案2】:
      $r = new ReflectionClass(get_class()); // or get_called_class
      foreach ($r->getInterfaceNames() as $name) {
          echo $name;
      }
      

      http://php.net/manual/en/reflectionclass.getinterfacenames.php

      【讨论】:

      • 谢谢,我认为反射类需要新的对象实例。无论如何感谢您的回答
      猜你喜欢
      • 2013-01-15
      • 2014-10-09
      • 1970-01-01
      • 2016-09-27
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多