|
| 1 | +--TEST-- |
| 2 | +Generic class: child inherits parent's generic constructor |
| 3 | +--FILE-- |
| 4 | +<?php |
| 5 | +declare(strict_types=1); |
| 6 | + |
| 7 | +class Box<T> { |
| 8 | + private T $value; |
| 9 | + public function __construct(T $value) { $this->value = $value; } |
| 10 | + public function get(): T { return $this->value; } |
| 11 | +} |
| 12 | + |
| 13 | +// Child with no constructor — inherits parent's |
| 14 | +class LabeledBox<T> extends Box<T> { |
| 15 | + public function label(): string { return "LabeledBox"; } |
| 16 | +} |
| 17 | + |
| 18 | +// Child with bound type and no constructor |
| 19 | +class IntBox extends Box<int> {} |
| 20 | + |
| 21 | +// Child with own constructor calling parent |
| 22 | +class NamedBox<T> extends Box<T> { |
| 23 | + private string $name; |
| 24 | + public function __construct(string $name, T $value) { |
| 25 | + $this->name = $name; |
| 26 | + parent::__construct($value); |
| 27 | + } |
| 28 | + public function getName(): string { return $this->name; } |
| 29 | +} |
| 30 | + |
| 31 | +// 1. Inherited constructor with explicit type args |
| 32 | +$lb = new LabeledBox<string>("hello"); |
| 33 | +echo "1. " . $lb->get() . " - " . $lb->label() . "\n"; |
| 34 | + |
| 35 | +// 2. Inherited constructor — type enforcement |
| 36 | +try { |
| 37 | + $lb2 = new LabeledBox<int>("not int"); |
| 38 | +} catch (TypeError $e) { |
| 39 | + echo "2. TypeError OK\n"; |
| 40 | +} |
| 41 | + |
| 42 | +// 3. Bound type with inherited constructor |
| 43 | +$ib = new IntBox(42); |
| 44 | +echo "3. " . $ib->get() . "\n"; |
| 45 | + |
| 46 | +try { |
| 47 | + $ib2 = new IntBox("not int"); |
| 48 | +} catch (TypeError $e) { |
| 49 | + echo "3. TypeError OK\n"; |
| 50 | +} |
| 51 | + |
| 52 | +// 4. Own constructor calling parent |
| 53 | +$nb = new NamedBox<float>("temp", 98.6); |
| 54 | +echo "4. " . $nb->getName() . ": " . $nb->get() . "\n"; |
| 55 | + |
| 56 | +// 5. Inferred type through explicit type args on child |
| 57 | +$lb3 = new LabeledBox<int>(42); |
| 58 | +echo "5. " . $lb3->get() . " - " . $lb3->label() . "\n"; |
| 59 | + |
| 60 | +try { |
| 61 | + $lb3->get(); // returns int, fine |
| 62 | + echo "5. class: " . get_class($lb3) . "\n"; |
| 63 | +} catch (TypeError $e) { |
| 64 | + echo "FAIL: " . $e->getMessage() . "\n"; |
| 65 | +} |
| 66 | + |
| 67 | +echo "Done.\n"; |
| 68 | +?> |
| 69 | +--EXPECT-- |
| 70 | +1. hello - LabeledBox |
| 71 | +2. TypeError OK |
| 72 | +3. 42 |
| 73 | +3. TypeError OK |
| 74 | +4. temp: 98.6 |
| 75 | +5. 42 - LabeledBox |
| 76 | +5. class: LabeledBox |
| 77 | +Done. |
0 commit comments