I have a class that sets up a class alias for other class names. When a function is called inside of this class via the aliased class, I need to know which alias was used. Is there a way to do this in PHP?
I have tried the following code:
class foo
{
public static function test()
{
var_dump(get_called_class());
}
}
class_alias('foo', 'bar');
foo::test();
bar::test();
Which outputs:
string 'foo' (length=3)
string 'foo' (length=3)
But I want bar::test(); to output string 'bar' (length=3) instead. Grasping at straws, __CLASS__ and get_class() all produce the same result. I can’t seem to find anything else in the PHP documentation that would help me with this problem, but hopefully I am overlooking something.
How do you get the called aliased class when using class_alias?
You can’t do this easily as of PHP 5.3-5.5.
There are only a handful of ways to determine what the “current” class is when a call is made. All of them return the unaliased class.
3v4l demo.
This is because
class_aliasdoesn’t create a new class with the new name, it creates another entry in the list of classes that points at the same class as the original. When you ask PHP to look up what class is being used, it finds the original class, not the alias.If you need to create a new class is nothing more the original class with a different name, you’ll need to do so via inheritance. You can do this dynamically using
eval. I can’t believe I’m going to recommendevalfor something. Eww.3v4l demo.
This might not work well for all cases. In PHP, private members can not be seen by descendant classes, so this might break your code horribly.