Skip to content

Instantly share code, notes, and snippets.

@krmgns
Created June 1, 2022 19:18
Show Gist options
  • Save krmgns/ab6129b70ee043dc8f30f945c4b08c69 to your computer and use it in GitHub Desktop.
Save krmgns/ab6129b70ee043dc8f30f945c4b08c69 to your computer and use it in GitHub Desktop.
Fake super() function for PHP, just like parent::__construct().
<?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