php anonymous classes

Anonymous Classes in PHP 7

PHP 7 comes with a bunch of features, from among these features is the anonymous classes, so now you can define classes without names in much the same way as closures or anonymous functions.


There are scenarios where you need to create classes at run time or in other means create classes on object initialization by passing parameters to the constructor let’s consider this example:

Now if we need to create another class for Female Gender one might create a new class but let’s define this using the anonymous class syntax:

So as you see above the anonymous class syntax is strait forward and it much like the normal class definition and all concepts that applies to normal classes also applies to anonymous classes.

In the code above we created a new class called Female which implements the same interface IGenderĀ then we implemented the only method getName(), after that we can access the class normally as if it be a normal class like this:


Basic Syntax


Retrieving class name

Note that anonymous class has a name assigned by the php engine, let’s display the anonymous class name using get_class():

If you var dump the class it will be like this one:


Passing constructor parameters

You can pass parameters to the class constructor during class initialization as shown in the following example:

As you see in the above code we pass three parameters to the class initialization code and then we passed them as the constructor arguments, as a result the php interpreter processes them and matches them with the supplied parameters.


Anonymous classes as type hint parameters

You can pass the definition of anonymous class as a parameter to type hinted constructors or other methods as dependency injection like this example:


Anonymous classes as function return value

You can return new instances of classes from functions, this concept applies also to anonymous classes consider this example:

As you see the power of this feature you can make use of this feature to develop a plugin system like in wordpress using anonymous classes.


Anonymous classes and inheritance

You can extend from other normal classes when using anonymous classes as shown in this example:

Using anonymous classes with interfaces and class inheritance

In fact you can implement interfaces, extend classes, pass arguments in the same manner as normal classes as shown below:


Share this: