PHP Reflection: identify correct constructor

Viewed 34

PHP ReflectionClass::getConstructor() gives a class's constructor.

If a child class has no constructor defined but its parent class does, then the parent constructor is returned.

Is there a way to distinguish whether the constructor came from a child class or its parent?

1 Answers

You can use the getParentClass method of the ReflectionClass class to determine the constructor function of each parent class by using recursion.

<?php

class point {
   function __construct($x) {$this->x=$x;}
}

class point2 extends point{
   function __construct($x,$y) {$this->x=$x;$this->y=$y;}
}

class point3 extends point2 {
  function __construct($x,$y,$z) {$this->x=$x;$this->y=$y;$this->z=$z;}
}

$ref= new ReflectionClass('point3');
do {
$constructor = $ref->getConstructor();
var_dump($constructor);}
while ($ref = $ref->getParentClass());
?>

Teh playground

This outputs:

object(ReflectionMethod)#3 (2) {
  ["name"]=>
  string(11) "__construct"
  ["class"]=>
  string(6) "point3"
}
object(ReflectionMethod)#2 (2) {
  ["name"]=>
  string(11) "__construct"
  ["class"]=>
  string(6) "point2"
}
object(ReflectionMethod)#4 (2) {
  ["name"]=>
  string(11) "__construct"
  ["class"]=>
  string(5) "point"
}

and by hashing out the various __construct functions, you can determine which ones are called.

Related