PHP - Class/Object class_alias() Function
The PHP Class/Object class_alias() function is used to create an alias name for the class. This means that you can rename a class and refer to it by either its original name or alias name. And most importantly aliased class has similar functionality like the original class.
Syntax
Below is the syntax of the PHP Class/Object class_alias() function −
bool class_alias ( string $class, string $alias, bool $autoload = true )
Parameters
Below are the parameters of the class_alias() function −
$class − It is the property that holds the original class name.
$alias − It is the alias name to give to the original class.
$autoload − Whether to autoload the class if it is not already loaded. Its default value is true.
Return Value
The class_alias() function returns TRUE on success and FALSE on failure.
PHP Version
First introduced in core PHP 5.3.0, the class_alias() function continues to function easily in PHP 7, and PHP 8.
Example 1
Here is the basic example of the PHP Class/Object class_alias() function to create an alias for a class and use it to initialize an object.
<?php
// Define the original class here
class MyClass {
public function hello() {
return "Hello from MyClass!";
}
}
class_alias('MyClass', 'AliasClass');
$obj = new AliasClass();
echo $obj->hello();
?>
Output
Here is the outcome of the following code −
Hello from MyClass!
Example 2
In the below PHP code we will use the class_alias() function and alias a class which belongs to a namespace.
<?php
// Define namespace here
namespace MyNamespace;
// Define a class here
class MyClass {
public function hello() {
return "Hello from MyNamespace\\MyClass!";
}
}
class_alias('MyNamespace\\MyClass', 'AliasClass');
$obj = new \AliasClass();
echo $obj->hello();
?>
Output
This will generate the below output −
Hello from MyNamespace\MyClass!
Example 3
In this PHP example, we create an alias for a class using the class_alias() function with a completely different class name.
<?php
// Define an original class here
class OriginalClass {
public function meet() {
return "Hello from OriginalClass! Nice to Meet You.";
}
}
class_alias('OriginalClass', 'DifferentClass');
$obj = new DifferentClass();
echo $obj->meet();
?>
Output
This will create the below output −
Hello from OriginalClass! Nice to Meet You.
Example 4
In the following example, we are using the class_alias() function and check if the class alias has been created using the if-else block.
<?php
// Define an original class here
class ExampleClass {
public function greet() {
return "Greetings from ExampleClass!";
}
}
$aliasCreated = class_alias('ExampleClass', 'AliasClass');
if ($aliasCreated) {
$obj = new AliasClass();
echo $obj->greet();
} else {
echo "Alias creation failed.";
}
?>
Output
Following is the output of the above code −
Greetings from ExampleClass!