phpclassoopinheritanceclass-hierarchy

Check if a class extends a different class in PHP


I have approximately this PHP code:

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();

I know that this code looks pretty unlogical, but I had to simplify it a lot. Anyway, the problem is, that the condition ($this::CLASS_NAMES['property'] instanceof self) always evaluates to false. Is there a way to check if a class (not its instance) extends or implements a different class/interface?


Solution

  • Use the is_subclass_of() function.

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