Backend Development

Anonymous Classes in PHP 7

php anonymous classes

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:

<?php

interface IGender 
{
    public function getName();
}

class Male implements IGender 
{
     public function getName()
     {
         return "male";
     }
}

$male = new Male();

echo $male->getName();

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:

$female = new class implements IGender {
    public function getName()
     {
         return "female";
     }
};

echo $female->getName();

// female

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:

$female->getName();

 

Basic Syntax

new class (optional parameters) extends other_class implements other_interface {
    
     ....
}

 

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():

echo get_class(new class());

// class@anonymous/opt/lampp/htdocs/test/anoynmous-classes/index.php0x7fa910187196

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

var_dump($female);

// object(class@anonymous)#1 (0) { } 

 

Passing constructor parameters

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

<?php

$car = new class(4, 1, 'BMW') {
    private $num_wheels;
    private $num_engines;
    private $model;

    function __construct($num_wheels, $num_engines, $model)
    {
        $this->num_wheels = $num_wheels;
        $this->num_engines = $num_engines;
        $this->model = $model;
    }

    public function getWheels()
    {
        return $this->num_wheels;
    }

    public function getEngines()
    {
        return $this->num_engines;
    }

    public function getModel()
    {
        return $this->model;
    }
}; 

echo $car->getWheels();
echo "<br/>";
echo $car->getEngines();
echo "<br/>";
echo $car->getModel();

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:

<?php

interface IValidator {
   public function handle();
}

class Application
{
     private $validator;

     public function setValidator(IValidator $validator)
     {
          $this->validator = $validator;
     }

     public function validate()
     {
         $this->validator->handle();
     }
}

$app = new Application();

$app->setValidator(new class implements IValidator {
    public function handle()
    {
        echo "desktop form validator executed";
    }
});

$app->validate();

$app->setValidator(new class implements IValidator {
    public function handle()
    {
        echo "mobile form validator executed";
    }
});



echo "<br/>";

$app->validate();

 

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:

<?php

function toast($message)
{
    return new class($message) {
      
     private $message;

      public function __construct($message)  
      {
          $this->message = $message;
      }

      public function display()
      {
         echo $this->message;
      }
    };
}

echo "<pre>";
toast("hello world")->display();
echo "<br/>";
var_dump(toast("hello world"));
echo "</pre>";

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:

class A
{
    private $name;   

    public function __construct($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }
}

$b = new class('anonymous') extends A
{
    public function getName()
    {
        return parent::getName() . ' class';
    }
};

echo $b->getName(), PHP_EOL;

// result: anonymous class

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:

<?php

$obj = new class($arg1, $arg2, $arg3, ...) extends otherClass implements interface1, interface2, ... 
{
      use SomeTrait;

      private $arg1;
      private $arg2;
      .....

      public function __construct($arg1, $arg2, ....)
     {
        $this->arg1 = $arg1;
        $this->arg2 = $arg2;
        ....
     }
};

 

3 3 votes
Article Rating

What's your reaction?

Excited
0
Happy
2
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Gufran Hasan
Gufran Hasan
4 years ago

Hi, Thanks,
Great article with full details.