如何在PHP中使用Reflection类获取扩展接口

发布于 2024-12-28 04:17:55 字数 479 浏览 2 评论 0原文

我有一个实现接口的类,并且该接口扩展了另一个接口。设置是这样的:

interface A{
}

interface B extends A {
}

class C implements B {
}


$obj = new C();

我想知道对象$obj实现了哪些接口。我尝试创建一个 ReflectionClass 对象,然后调用 getInterfaces 方法,但它只返回接口 B:

$reflection = new ReflectionClass($obj);
print_r($reflection->getInterfaces());

我还尝试使用接口名称创建一个 ReflectionClass 对象,但当我调用 getInterfaces() 方法时,它返回一个空大批。

你们中有人知道如何获取扩展给定接口的接口名称吗?

非常感谢您的帮助, 史蒂夫

I have a class that implements an interface, and that interface extends another interface. The setting is like that:

interface A{
}

interface B extends A {
}

class C implements B {
}


$obj = new C();

I want to know which interfaces the object $obj implements. I tried to create a ReflectionClass object and then calling the getInterfaces method, but it only returns me the interface B:

$reflection = new ReflectionClass($obj);
print_r($reflection->getInterfaces());

I also tried to create a ReflectionClass object using the interface name, but when I call the getInterfaces() method, it returns an empty array.

Does any of you guys know how to get an interface name that extends a given interface?

Thanks a lot for your help,
Steve

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

疾风者 2025-01-04 04:17:55

您不需要为此进行反射。您可以简单地使用

  • 实现的接口

class_implements — 返回给定类示例 你的代码片段:

var_dump(class_implements($obj));

输出:

array(2) {
  ["B"]=>
  string(1) "B"
  ["A"]=>
  string(1) "A"
}

You do not need Reflection for this. You can simply use

  • class_implements — Return the interfaces which are implemented by the given class

Example for your code snippet:

var_dump(class_implements($obj));

Output:

array(2) {
  ["B"]=>
  string(1) "B"
  ["A"]=>
  string(1) "A"
}
北方。的韩爷 2025-01-04 04:17:55
<?php
interface A {}
interface B extends A {}
class C implements B {}
$obj = new C();

$reflection = new ReflectionClass($obj);
echo "<pre>";
print_r($reflection->getInterfaces());
echo "</pre>";

您的示例为我输出以下内容(IDE 调试器在 PHP 5.2.17 上运行):

Array
(
    [B] => ReflectionClass Object
        (
            [name] => B
        )

    [A] => ReflectionClass Object
        (
            [name] => A
        )

)
<?php
interface A {}
interface B extends A {}
class C implements B {}
$obj = new C();

$reflection = new ReflectionClass($obj);
echo "<pre>";
print_r($reflection->getInterfaces());
echo "</pre>";

Your example outputs this for me (IDE debugger is running on PHP 5.2.17):

Array
(
    [B] => ReflectionClass Object
        (
            [name] => B
        )

    [A] => ReflectionClass Object
        (
            [name] => A
        )

)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文