Home » PHP Anonymous Classes : A Tutorial with Examples

PHP Anonymous Classes : A Tutorial with Examples

Anonymous classes in PHP are useful when you need to create a class only once, often for short-lived purposes, and you don’t want to define a named class.

Anonymous classes were introduced in PHP 7 and are particularly useful for simple objects, such as callbacks or mock objects, without the need for a full class definition.

In this tutorial, we will cover:

Let’s explore each of these concepts with examples and explanations.

1. What is an Anonymous Class?

An anonymous class is a class without a name. It can be used to create objects on the fly for a specific task, without the need to define a formal class.

Anonymous classes are ideal for scenarios where the class is only needed once or for a short time.

Syntax:

new class {
    // Class properties and methods
};

Example (Simple Anonymous Class):

<?php
// Create an anonymous class and assign it to a variable
$object = new class {
    public $greeting = "Hello, World!";
};

// Access the property
echo $object->greeting;  // Outputs: Hello, World!
?>
  • In this example, an anonymous class is created and assigned to the variable $object. The class has a public property $greeting that is accessed and printed.

2. Creating and Using Anonymous Classes

You can create anonymous classes and use them just like regular classes, including defining properties and methods. Anonymous classes are typically created with the new keyword followed by the class definition.

Example (Anonymous Class with Properties and Methods):

<?php
// Create an anonymous class with properties and methods
$object = new class {
    public $name = "Anonymous";
    
    public function greet() {
        return "Hello from " . $this->name . "!";
    }
};

// Call the method
echo $object->greet();  // Outputs: Hello from Anonymous!
?>
  • In this example, the anonymous class has a property $name and a method greet(). The method is called to display the greeting message.

3. Anonymous Classes with Constructor and Methods

Just like regular classes, anonymous classes can have constructors, methods, and properties. You can pass arguments to the constructor of an anonymous class at the time of instantiation.

Example (Anonymous Class with a Constructor):

<?php
// Create an anonymous class with a constructor
$object = new class("John") {
    public $name;

    // Constructor to initialize the name
    public function __construct($name) {
        $this->name = $name;
    }

    public function greet() {
        return "Hello, " . $this->name . "!";
    }
};

// Call the method
echo $object->greet();  // Outputs: Hello, John!
?>
  • In this example, the anonymous class has a constructor that accepts a $name argument and initializes it. The method greet() returns a personalized greeting.

4. Passing Anonymous Classes as Function Arguments

Anonymous classes can be passed directly as function arguments, making them useful for quick, one-time objects such as callbacks or event handlers.

Example (Passing Anonymous Class to a Function):

<?php
// Function that accepts an object with a greet method
function sayHello($obj) {
    echo $obj->greet();
}

// Pass an anonymous class as an argument
sayHello(new class {
    public function greet() {
        return "Hello from an anonymous class!\n";
    }
});
?>
  • In this example, an anonymous class is passed directly as an argument to the sayHello() function. The function calls the greet() method of the anonymous class.

5. Using Anonymous Classes with Interfaces

Anonymous classes can implement interfaces just like regular classes. This makes them useful for scenarios where you need to adhere to a specific contract but don’t want to define a full class.

Example (Anonymous Class Implementing an Interface):

<?php
// Define an interface
interface Greeter {
    public function greet();
}

// Create an anonymous class that implements the interface
$object = new class implements Greeter {
    public function greet() {
        return "Hello from an anonymous class implementing an interface!";
    }
};

// Call the method
echo $object->greet();
?>
  • In this example, the anonymous class implements the Greeter interface. The greet() method is implemented, and the class adheres to the interface contract.

6. Anonymous Classes with Traits

Anonymous classes can also use traits, allowing them to share reusable functionality just like regular classes.

Example (Anonymous Class Using a Trait):

<?php
// Define a trait
trait Logger {
    public function log($message) {
        echo "Log: $message\n";
    }
}

// Create an anonymous class that uses the Logger trait
$object = new class {
    use Logger;

    public function greet() {
        $this->log("Greeting executed.");
        return "Hello from an anonymous class with a trait!";
    }
};

// Call the method
echo $object->greet();
?>
  • In this example, the anonymous class uses the Logger trait. The class has a greet() method that logs a message using the log() method from the trait.

7. Example Use Case: Anonymous Class for Simple Logger

Let’s create a practical example where an anonymous class is used as a simple logger. The logger will write messages to a file.

Example (Anonymous Class for Logging):

<?php
// Define a function that accepts a logger object
function logMessage($logger, $message) {
    $logger->log($message);
}

// Create an anonymous class for logging
$logger = new class("log.txt") {
    private $file;

    public function __construct($filename) {
        $this->file = fopen($filename, 'a');
    }

    public function log($message) {
        $timestamp = date("Y-m-d H:i:s");
        fwrite($this->file, "[$timestamp] $message\n");
    }

    public function __destruct() {
        fclose($this->file);
    }
};

// Log a message using the anonymous class
logMessage($logger, "This is a test log entry.");
logMessage($logger, "Another log entry.");
?>
  • In this example, an anonymous class is created to log messages to a file (log.txt). The class has a constructor to open the file and a log() method to write messages with timestamps. When the script ends, the __destruct() method closes the file.

Contents of log.txt:

[2024-10-17 12:34:56] This is a test log entry.
[2024-10-17 12:35:12] Another log entry.

Summary of PHP Anonymous Classes:

Concept Description
Anonymous Class Syntax new class { /* class definition */ };
Properties and Methods Anonymous classes can have properties, methods, and constructors.
Using with Interfaces Anonymous classes can implement interfaces.
Using with Traits Anonymous classes can use traits to reuse functionality.
Passing as Function Arguments Anonymous classes can be passed as function arguments.
Destructors You can use the __destruct() method in anonymous classes to handle cleanups.

Conclusion

Anonymous classes in PHP are a powerful tool for creating lightweight, one-time-use objects.

They allow you to define classes without a name and are perfect for situations where a class is only needed temporarily.

In this tutorial, we covered:

  • Creating and using anonymous classes with properties, methods, and constructors.
  • Passing anonymous classes as function arguments for callbacks or one-off operations.
  • Implementing interfaces and using traits in anonymous classes.
  • A practical example of using an anonymous class as a logger.

You may also like