• Date: June 12, 2011
  • Author: Slawek Lukasiewicz
  • Comments: 3 Comments
  • Category: PHP

Sometimes we need to use external libraries with strange and obscure class names, and it can be really annoying. Luckily, from PHP 5.3 version we can create aliases for classes and interfaces with class_alias function.

Example of class_alias usage.

class Irrational_Long_Class_Name
{
 // empty class
}
 
class_alias('Irrational_Long_Class_Name', 'ShortAlias');
 
$shortAliasInstance = new ShortAlias();
var_dump( $shortAliasInstance instanceof Irrational_Long_Class_Name);
# true
var_dump( $shortAliasInstance instanceof ShortAlias);
# true

I was initially worried about behavior of get_class function, but everything works as expected – and get_class returns original class name.

class Irrational_Long_Class_Name
{
 
	public function getClass()
	{
		print get_class();
	}
}
 
class_alias('Irrational_Long_Class_Name', 'ShortAlias');
 
$aInstanceWithAlias = new ShortAlias();
 
$aInstanceWithAlias->getClass();
#  Irrational_Long_Class_Name
print get_class($aInstanceWithAlias);
# Irrational_Long_Class_Name

Also type hinting is aware of aliases.

class TestClass
{
	public function doSomethingWithShortAliasInstance(ShortAlias $b) { }
}
class_alias('Irrational_Long_Class_Name', 'ShortAlias');
$aInstanceWithAlias = new ShortAlias();
$testClassInstance = new TestClass();
$testClassInstance->doSomethingWithShortAliasInstance($aInstanceWithAlias);
# everything is correct

Namespaces aliasing
As Jani mentioned below – namespaces aliasing also can be solution.

use \Irrational_Long_Class_Name as ShortAlias;

3 Responses to “Create alias for class”

  1. Why not just use

    use Long_Class_Name as SomeAlias;
  2. Slawek Lukasiewicz says:

    In some cases we can use namespaces aliasing – class_alias is better when we want to create alias for whole application.

  3. Ah, didn’t consider that class_alias does it app-wide. Might easily lead to some confusion about what is what if it’s used like that though.

Leave a Reply →