PHP Classes

PHP 7 Anonymous Classes Tutorial

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog PHP 7 Anonymous Class...   Post a comment Post a comment   See comments See comments (5)   Trackbacks (0)  

Author:

Viewers: 2,882

Last month viewers: 330

Categories: PHP Tutorials

PHP 7 has introduced a new class feature called the Anonymous Class which allow us to create objects without the need to name them.

Read this article to learn about the concept behind anonymous classes and how we can use them in your PHP projects.




Loaded Article

Contents

Introduction

What is in a name?

The One-Off Object

Conclusion

PHP 7 logo

Introduction

This article assumes you have a working knowledge of Classes and Objects within PHP. At the most fundamental level an Anonymous Class is simply a class definition without a name. It is defined just like any other class. In truth, they do have internally generated names so we do not need to provide the names.

Anonymous Classes

What is in a name?

We should all be familiar with what a named class looks like

class className {

 // defined properties and methods

};

$object = new className( 'arguments' );

An anonymous class is closely related to a named class, with the primary difference being that we instantiate it without a name.

$object = new class( 'arguments' ) {

 // defined properties and methods
};

As you can see here, we have created a new object at the same time we defined the class. The arguments in each case are passed to the defined constructor method.

The One-Off Object

Currently the PHP manual states that anonymous classes are useful when simple, one-off objects need to be created. What exactly do they mean?

You certainly could create a complex anonymous class, however if you wanted to take advantage of inheritance you would need a named class to extend.

The flip side of that coin is when you have a named class and want to create a simple object to use during the current execution.

For example you may need to override a property or method, you could create a new class that extends the named class, however that is the old way. The new way would be to create an anonymous class when you need that simple, one-off object.

class namedClass {
    
protected $classType;
 protected $myProp = 'I am a named object';
    
 public function __construct($value) {
        
  $this->classType = $value;
        
 }
    
 public function returnProperty( $propName ) {
        
  if( !empty( $this->$propName ) ) {
            
   return $this->$propName;
            
  } else {
            
   return 'property not found';
            
  }
 }
    
}

This is a simple example of a named class which has two properties. When the class is instantiated, classType is assigned from a passed value and myProp is assigned in the class. It also has a method to return the value of any requested property by name.

$object = new namedClass( 'Named' );
echo $object -> returnProperty( 'classType' ); // Named
echo $object -> returnProperty( 'myProp' ); // I am a named object

Here we have instantiated a namedClass, assigning the value 'Named' to the classType property. Using the returnProperty method we can get the values assigned to the properties of the object.

In the next example, we will take it a step further and override the myProp property by extending the class using the old way.

class namedExtension extends namedClass {
    
    protected $myProp = 'I am an extended object';
    
} $object = new namedExtension( 'Extended' ); echo $object -> returnProperty( 'classType' ); //Extended echo $object -> returnProperty( 'myProp' ); //I am an extended object

As we can see here, we have instantiated a namedExtension of the namedClass, assigning the value 'Extended' to the classType property and overriding the myProp value.

So far there is nothing new here, this is how we have been working with classes in PHP. Now let us take a look at interacting with the namedClass anonymously, the new way.

$object = new class( 'Anonymous' ) extends namedClass {
    
    protected $myProp = 'I am an anonymous object';
};
echo $object -> returnProperty( 'classType' ); // Anonymous echo $object -> returnProperty( 'myProp' ); // I am an anonymous object

Here we have created the object with an anonymous class. It is worth noting that the value 'Anonymous' used here is the argument passed to the constructor and not the class name. The syntax, new class, instantiates the anonymous class where instantiating a named class uses, new className.

One advantage is that we no longer need the named extension. Normally the named extension would be hidden away in some included file, if you ever needed to see how it is defined you have to start searching for it. With anonymous classes the definition is in the same place the object is created.

Conclusion

The anonymous class can be used just like any other class can as we have seen in this example to extend a class.

You can also implement interfaces and use traits for better code reuse. An exciting new feature is that they can also be nested inside classes, the first step to nested named classes. We will dive into nested classes in an upcoming article.

If you liked this article or you have questions about anonymous classes, post a comment here.




You need to be a registered user or login to post a comment

Login Immediately with your account on:



Comments:

3. A real usecase - iltar van der berg (2015-10-15 18:56)
One time used value objects... - 0 replies
Read the whole comment and replies

2. Thanks for an overview - Vallo Reima (2015-10-14 06:37)
Useful dynamic features... - 1 reply
Read the whole comment and replies

1. Thanks for a great article! - Steve (2015-10-13 22:36)
I learned more about 'basic' classes - and php7 anon class too!... - 1 reply
Read the whole comment and replies



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog PHP 7 Anonymous Class...   Post a comment Post a comment   See comments See comments (5)   Trackbacks (0)