Created
June 1, 2022 19:18
-
-
Save krmgns/ab6129b70ee043dc8f30f945c4b08c69 to your computer and use it in GitHub Desktop.
Fake super() function for PHP, just like parent::__construct().
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function super(...$args) { | |
$object = debug_backtrace(1, 2)[1]['object']; | |
$parent = get_parent_class($object); // Let it errorize. | |
if ($parent && method_exists($parent, '__construct')) { | |
$ref = new ReflectionMethod($parent, '__construct'); | |
$ref->invoke($object, ...$args); | |
} | |
} | |
class Foo { | |
var $x; | |
function __construct($x) { | |
$this->x = $x; | |
} | |
} | |
class SubFoo extends Foo { | |
function __construct($x = null) { | |
super($x ?? 123); | |
} | |
} | |
var_dump(new SubFoo()); | |
var_dump(new SubFoo(456)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment