Class and interface aliases in PHP

I was asked by a friend if it’s possible to create aliases for classes and interfaces in PHP, the answer is yes but there are some restrictions.


So, without further ado, let’s create an alias for a class.


<?php

// Create an alias for a class; requires PHP version >= 5.3.

class User
{

	const CLASS_NAME = __CLASS__;

}

// Creates an alias called "UserAlias" for the class "User".
class_alias( 'User', 'UserAlias' );

$user = new User;
$userAlias = new UserAlias;

var_dump( $user instanceof User ); // true
var_dump( $user instanceof UserAlias ); // true
var_dump( $userAlias instanceof User ); // true
var_dump( $userAlias instanceof UserAlias ); // true

echo User::CLASS_NAME; // Prints "User".
echo PHP_EOL;
echo UserAlias::CLASS_NAME; // Prints "User" NOT "UserAlias".

You can use the same function class_alias( ... ) to create aliases for interfaces.


<?php

// Create an alias for an interface; requires PHP version >= 5.3.

interface UserInterface
{

	const INTERFACE_NAME = __CLASS__;

}

// Creates an alias called "UserI" for the interface "UserInterface".
class_alias( 'UserInterface', 'UserI' );

class User implements UserI {}

$user = new User;

var_dump( $user instanceof UserInterface ); // true
var_dump( $user instanceof UserI ); // true

echo User::INTERFACE_NAME; // Prints "UserInterface" NOT "UserI".

Now, let’s talk about the restrictions. You can ONLY create aliases for user defined classes and interfaces; you can NOT create aliases for classes and interfaces defined by PHP or PHP extensions.


<?php

// Create an alias for a class defined by PHP; requires PHP version >= 5.3.

// Try to create an alias called "ArrayObjectAlias" for the built-in class "ArrayObject".
class_alias( 'ArrayObject', 'ArrayObjectAlias' );

new ArrayObjectAlias;

If you execute the code above, you will get the following errors.

  1. PHP Warning: First argument of class_alias() must be a name of user defined class in /home/jason/Projects/Sandbox/index.php on line 6
  2. PHP Fatal error: Class ‘ArrayObjectAlias’ not found in /home/jason/Projects/Sandbox/index.php on line 8

If you must create aliases for built-in classes and interfaces, you can use inheritance to achieve the goal of using another name for a built-in class or interface.


<?php

class ArrayObj extends ArrayObject {}

new ArrayObj;

In object-oriented programming, inheritance is a way to reuse code of existing objects or to create a subtype from an existing object. So, using inheritance to create aliases is a hack and I do NOT recommend doing this.

OK, that’s it for now. Leave your comments or questions below.