PHP/inheritance

from HTYP, the free directory anyone can edit if they can prove to me that they're not a spambot
< PHP
Revision as of 13:06, 5 April 2024 by Woozle (talk | contribs)
Jump to navigation Jump to search

About

PHP includes a few bits of functionality for checking whether an object or class inherits from another class or interface. The rules for this functionality are not always clearly explained.

Class Inheritance Functions Testing

Here's a truth-table from PHP 8.2.10:

arguments B instanceof A is_a(B,A,FALSE) is_a(B,A,TRUE) is_subclass_of(B,A,FALSE) is_subclass_of(B,A,TRUE)
cA, cA - - Y - -
cB, cA - - Y - Y
$oA, cA Y Y Y - -
$oB, cA Y Y Y Y Y
cA, iA - - Y - Y
$oA, iA Y Y Y Y Y
cB, iA - - Y - Y
$oB, iA Y Y Y Y Y
cB, iB - - Y - Y
$oB, iB Y Y Y Y Y
cA, tA - - - - -
cB, tA - - - - -
$oB, tA - - - - -
cD, cA - - - - -
$oD, cA - - - - -

Code for entities used in the test:

interface iA {}
interface iB extends iA {}            // interface B inherits from interface A
trait tA {}
class cA implements iA { use tA; }    // class A inherits from iA and tA
$oA = new cA;                         // object of class A
class cB extends cA implements iB {}  // class B inherits from cA and iB
$oB = new cB;                         // object of class B
class cD {}                           // unrelated class
$oD = new cD;                         // object of class D

Conclusions:

  • Nothing sees traits as parent-classoids.
  • is_a(A,B,FALSE) is useless unless A is an object (always returns FALSE).
  • is_subclass_of() is the same as is_a(A,B) except it will return FALSE if cA (aka $oA's class) is the same as cB.