【问题标题】:Check if a class extends a different class in PHP检查一个类是否在 PHP 中扩展了不同的类
【发布时间】:2021-02-03 18:02:46
【问题描述】:

我有大约这个 PHP 代码:

class DatabaseItem
{
  private const CLASS_NAMES = null;
  public function doStuff()
  {
    if ($this::CLASS_NAMES['property'] instanceof self)
    {
      //Construct the Profile Picture object and save it into the property of the $user instance
    }
  }
}

class ProfilePicture extends DatabaseItem { /* Unimportant stuff */ }

class User extends DatabaseItem
{
  protected const CLASS_NAMES = array('property' => ProfilePicture);

  protected $profilePic;
}

$user = new User();
$user->doStuff();

我知道这段代码看起来很不合逻辑,但我不得不对其进行大量简化。无论如何,问题是,条件($this::CLASS_NAMES['property'] instanceof self) 总是评估为假。有没有办法检查一个类(不是它的实例)是否扩展或实现了不同的类/接口?

【问题讨论】:

  • instanceof 的第二个操作数应该是类,而不是类实例。
  • 我认为你只是把它倒过来了:$this instanceof $this::CLASS_NAMES['property']
  • doStuff() 需要 $user 参数,但您使用空参数列表调用它。
  • 感谢您的回复,但问题是,我没有任何类的实例。我只知道他们的名字。结果,我不能使用 $this。在示例中,我试图找出 ProfilePicture 类是否扩展了 DatabaseItem 类,它确实如此。关于缺少的 $user 参数,这只是一个错字,已经修复了。
  • array('property' => ProfilePicture) ProfilePicture 的常量。你的意思是ProfilePicture::class

标签: php class oop inheritance class-hierarchy


【解决方案1】:

我尝试了你的建议,但对我有用的是改变

protected const CLASS_NAMES = array('property' => ProfilePicture);

protected const CLASS_NAMES = array('property' => ProfilePicture::class);

然后改变

if ($this::CLASS_NAMES['property'] instanceof self)

if (is_subclass_of($this::CLASS_NAMES['property'], __CLASS__))

所以我一次使用了你所有的答案。非常感谢您的帮助。

附:我不确定我是否应该在 cmets 中发布此内容,但我认为结论应该清晰可见。

【讨论】:

    【解决方案2】:

    使用is_subclass_of() 函数。

    if (is_subclass_of(self::CLASS_NAMES['property'], get_class($this)))
    

    【讨论】:

    • this comment 表示版本 >= 5.5。
    • 啊,这仅适用于文字类名,不适用于变量。
    • 哦,酷!它看起来像我需要的。只是一个小问题:我可以使用self 而不是$this::class 吗?它对我来说看起来更流畅,但我不确定我是否可以做到。
    • 当然,我只是混淆了不同的语言。
    • $self 是一个和其他变量一样的变量。 if (is_subclass_of(self::CLASS_NAMES['property'], __CLASS__)) 可能就是你的意思,Barmar。但在那种情况下它不会起作用,因为CLASS_NAMESDatabaseItem 中为空,所以我认为你之前的答案是正确的。
    猜你喜欢
    • 2013-04-09
    • 1970-01-01
    • 2015-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多