PHP 7 – Anonymous Classes

In PHP 7, another new feature Anonymous Class has been introduced.

An anonymous class is a class which has no name. It is defined using new class keyword.

When to use Anonymous Class?

  • Anonymous class is used when class does not need to be documented.
  • When the class is used only once during execution.
  • When the object is required to create only once in a program, then anonymous class is used.
<?php

$obj = new class(20) {

    private $x;

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

    function add($y) {
        return $this->x + $y;
    }
    
    function sub($y){
        return $this->x - $y;
    }
};

$result = $obj->add(40);
echo "Sum = $result <br>";

$result = $obj->sub(10);
echo "Subtraction = $result <br>";

?>

Output:
Sum = 60
Subtraction = 10
Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial