QRdvark.com

Anonymous Classes With PHP

Anonymous Classes With PHP

  1. Abstract
  2. What are Anonymous Classes?
  3. Passing Arguements To an Anonymous Function
  4. Extending With an Anonymous Class
  5. Anonymous Functions as Class Properties.
  6. Type Hinting

Abstract

With the advent of PHP 7 came Anonymous Clases. Quite often referred to as the module pattern, anonymous classes are a design pattern frequently used in languages such as javascript. In PHP, these are essentially all the same.

What Are Anonymous Classes?

In PHP, an Anonymous Class is a class which is created on-the-fly. Usually this is for a single call and allows assigning the value to a variable, or class property. Consider this starter:


<?php

// Example of a single use anonymous class
$log = (new class {
    public function 
log($msg)
    {
        
// echo the log message
        
echo $msg;
    }
});
// call the log function within the anonymous class.
$log->log"This is not a love song\n" );
?>

The above code will output the following.

This is not a love song

This example is rather simple, but shows how PHP anonymous classes can be used where a disposable object is required.

Passing Arguements to an Anonymous Class

As we saw above, an anonymous classes can be assigned to a variable. This variable, can be used as an arguement to another function, and you can even pass arguements to the constructor of an anonymous class, or any anonymous class method.


<?php

// a message to pass to the constructor
$message "This is a log message\n";

// create a new anonymous class, and pass the message as an arguement to the constructor
$log = (new class( $message ) {
        
/**
         * Constructor, Duh!
         * @access      public
         * @param       string  $message
         */
        
public function __construct$message )
        {
                
// echo the message
                
echo $message;
        }
});
?>

In the above code, a message variable is set, which is then used as an arguement to the constructor of the anonymous class. In the __construct() method, the variable can be used as with any class. To take this one step further, the possibilities are far reaching.

Extending With an Anonymous Class

In this example, the anonymous class extends a parent class, to show the versatility of anonymous classes.


<?php

/**
 * Class that will be extended
 */
class myClass{

        
/**
         * Constructor, Duh!
         * @access      public
         * @param       string  $message
         */
        
public function __construct$message )
        {
                
// echo the message
                
echo $message;
        }
}

// a message to pass to the constructor
$message "This class extends myClass\n";

// a new anonymous class, which extends the myClass class.
$log = (new class( $message ) extends myClass{
        public function 
__construct$message )
        {
                
// call the parent, myClass constructor
                
parent::__construct$message );
        }
});

The above code allows an anonymous class to extend the myClass class, and pass an arguement to the constructor of the myClass class. Lets take this just one more step, and see how an object might be used, when passed to the constructor of the parent class.

Passing objects to parent classes

The above example showed a simple method of using an anonymous class to pass an string as an aguement to teh constructor. This can be taken one step further to show how this might be useful when only a single call to a class (disposable class) is required.


<?php

class db{

        public function 
__constructconfig $config )
        {
                echo 
"Connecting to $config->db_name\n";
                echo 
"Connecting with $config->db_user\n";
                echo 
"Connecting with $config->db_pass\n";
        }
}

class 
config{

        public 
$db_name 'QRdvark';
        public 
$db_user 'bigkev';
        public 
$db_pass 'my_pass';
}
$config = new config;

// anonymous class extends the db class, and passes config object as arguement to constructor.
$db = ( new class( $config ) extends db
        
{
                public function 
__construct$config )
                {
            
// call the parent db class constructor
                        
parent::__construct$config );
                }
        });

The code above will output the following..

Connecting to QRdvark
Connecting with bigkev
Connecting with my_pass

A config instance is created using the well known new config and this object is then used by the anonymous class as an arguement to pass to the parent, db class. The db class could use these values to connect to, or create a database connection, or pretty much anything.

Note in the db class the use of type hint in the constructor which ensures the object being passes as an arguement is of type config. Any other class would produce an error.