Check if a class extends a different class in PHP

740 views Asked by At

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?

2

There are 2 answers

9
Barmar On BEST ANSWER

Use the is_subclass_of() function.

if (is_subclass_of(self::CLASS_NAMES['property'], get_class($this)))
0
Shady Medic On

I tried your suggestions and what worked for me was changing

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

and then changing

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

So I used all of your answers at once. Thanks a lot for your help.

P.S. I am not sure if I shouldn't post this in comments, but I thought that a conclusion should be clearly visible.