PHP/inheritance

from HTYP, the free directory anyone can edit if they can prove to me that they're not a spambot
< PHP
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)
compare things to cA
cA, cA - - Y - -
cB, cA - - Y - Y
$oA, cA Y Y Y - -
$oB, cA Y Y Y Y Y
compare things to iA
cA, iA - - Y - Y
$oA, iA Y Y Y Y Y
cB, iA - - Y - Y
$oB, iA Y Y Y Y Y
compare things to iB
cB, iB - - Y - Y
$oB, iB Y Y Y Y Y
compare things to tA
cA, tA - - - - -
cB, tA - - - - -
$oB, tA - - - - -
compare xD to things (should always be FALSE)
cD, cA - - - - -
$oD, cA - - - - -

Code just for entities used in the test (full code is here):

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 parents.
  • 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.