【问题标题】:A function to determine whether one type extends or inherits another in PHP?确定一种类型是否在 PHP 中扩展或继承另一种类型的函数?
【发布时间】:2009-12-03 08:08:22
【问题描述】:

PHP 中有没有办法知道一个类是否继承另一个类?

class Controller
{
}

class HomeController extends Controller
{
}

class Dummy
{
}

// What I would like to do

    $result = class_extends('HomeController', 'Controller'); /// true
    $result = class_extends('Dummy', 'Controller'); /// false

【问题讨论】:

  • @ChristopheD 你的想法是对的。

标签: php oop


【解决方案1】:

您需要使用instanceof

请注意implements 不正确。 instanceof 应该在两种情况下都使用(检查对象是否是继承的类,或者对象是否实现了接口)。

手册示例:

<?php
interface MyInterface
{
}

class MyClass implements MyInterface
{
}

$a = new MyClass;

var_dump($a instanceof MyClass);
var_dump($a instanceof MyInterface);
?>

给予:

bool(true)
bool(true)

【讨论】:

  • 是的,我知道。我不知道我在想什么。深夜在这里;)
  • 哈哈...我正要发表评论,但是当我自己点击提交时,您已经修复了它。 :D
【解决方案2】:

是的,你可以使用

if ($foo instanceof ClassName)
    // do stuff...

编辑:据我所知,这甚至应该适用于接口......

【讨论】:

【解决方案3】:

我可以推荐instanceof operator吗?

class A { }
class B extends A { }
class C { }

$b = new B;
$c = new C;

var_dump($b instanceof A, $c instanceof A) // bool(true), bool(false)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-30
    • 1970-01-01
    • 2019-10-25
    • 1970-01-01
    • 1970-01-01
    • 2011-05-04
    • 1970-01-01
    • 2021-06-13
    相关资源
    最近更新 更多