A class in OOP is an abstraction of a real-life group of similar items. It presents a blueprint from which objects can be created.
class my_class_name{
//some logic;
};
The name given to this class, my_class_name
, is used to create its object(s) or to refer to it. However, we can give another name to this class that references the same class. To do this, we can use the class_alias()
function provided by PHP.
This PHP function is used to create a temporary name for a class. This temporary name does not mean a change in the class nor does it indicate what it does, but it provides a reference to the class that is aliased.
class_alias($class,$alias,$autoload)
$class
: This is a data type of string and is the name of the class that is to be aliased.$alias
: This is also a string, which refers to the name we wish to use as the alias.$autoload
: This is a boolean value of True
or False
, which checks whether to autoload or not, if the original class is not found. When set as True
, it implies that when the class indicated is not explicitly loaded with the require()
, require_once()
, include()
, or include_once()
functions, it will be automatically loaded by the PHP parser. However, this will not happen if it is set as False
.The return value of this function is a boolean value. It returns True
if it is successful in creating an alias. Conversely, it returns False
if it fails to create an alias.
Let’s look at an example:
<?phpclass myClass { }class_alias('myClass', 'myClass_alias');$pink= new myClass;$blue = new myClass_alias;//The output from these checks below are boolean// checking that the objects are the samevar_dump($pink == $blue);var_dump($pink === $blue);var_dump($pink instanceof $blue);/* trying different intances to confirmthe classes are the same*/var_dump($pink instanceof myClass);var_dump($pink instanceof myClass_alias);var_dump($blue instanceof myClass);var_dump($blue instanceof myClass_alias);?>
Lines 4–9: We create a class called myClass
, as well as an alias for it named myClass_alias
. Then, we create the objects $pink
and $blue
. The former is from the main class and the latter is from the alias class.
Lines 13–14: We check the equality of the newly-created objects and output to the screen, using the var_dump()
function.
Line 16: We compare the objects, using the keyword instanceof
, to ascertain the equality of the two objects as being from the same parents. Here, it returns False
because both the parameters are objects.
Lines 21–24: We use the instanceof
keyword to check if these two objects are instances of both the classes. The output of the code returns True
.
Note: Aliases, as always, are for convenience. They do not change the aliased class in any way.