In PHP, how do you get the aliased class being called when using class_alias?

I have a class that sets the class alias for other class names. When a function is called inside this class through a class with an alias, I need to know which alias was used. Is there a way to do this in PHP?

I tried the following code:

class foo { public static function test() { var_dump(get_called_class()); } } class_alias('foo', 'bar'); foo::test(); bar::test(); 

What outputs:

 string 'foo' (length=3) string 'foo' (length=3) 

But I want bar::test(); output string 'bar' (length=3) . Grabbing on straws, __CLASS__ and get_class() all give the same result. I cannot find anything else in the PHP documentation that would help me with this problem, but I hope I don’t notice something.

How to get a class named aliased when using class_alias?

+6
source share
1 answer

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(); // First $aliased->test2(); // array( 0 => array( ... [object] => First Object, ... ) ) $aliased->test3(); // First $aliased->test4(); // First Second::test5(); // First 

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(); // Second $aliased->test2(); // array( 0 => array( ... [object] => Second Object, ... ) ) $aliased->test3(); // Second $aliased->test4(); // First (this is expected) Second::test5(); // Second 

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.

+7
source

Source: https://habr.com/ru/post/908152/


All Articles