You cannot do this easily with PHP 5.3-5.5.
There are only a few ways to determine what the "current" class is when called. They all return an unconvinced class.
class First { public function test1() { echo get_called_class(); } public function test2() { print_r(debug_backtrace()); } public function test3() { echo get_class($this); } public function test4() { echo __CLASS__; } public static function test5() { echo get_called_class(); } } class_alias('First', 'Second'); $aliased = new Second(); $aliased->test1();
3v4l demo .
This is because class_alias
does not create a new class with a new name, it creates another entry in the list of classes that points to the same class as the original. When you ask PHP to see which class is used, it finds the source class, not an alias.
If you need to create a new class, this is no more the original class with a different name, you need to do this through inheritance. You can do this dynamically using eval
. I can not believe that I would recommend eval
for something. Eww.
class First { public function test1() { echo get_called_class(); } public function test2() { print_r(debug_backtrace()); } public function test3() { echo get_class($this); } public function test4() { echo __CLASS__; } public static function test5() { echo get_called_class(); } } function class_alias_kinda($original, $alias) { eval("class $alias extends $original {}"); } class_alias_kinda('First', 'Second'); $aliased = new Second(); $aliased->test1();
3v4l demo .
This may not work for all cases. In PHP, private members cannot be seen by descendant classes, so this can break your code a lot.
source share