PHP — Classes and Objects
Basic anonymous class
<?php
$obj = new class {
public function greet(): string {
return "Hello from anonymous class!";
}
};
echo $obj->greet();
?>
With constructor
<?php
$obj = new class("Alice", 30) {
public function __construct(
private string $name,
private int $age
) {}
public function getInfo(): string {
return "{$this->name} is {$this->age}";
}
};
echo $obj->getInfo(); // Alice is 30
?>
Implementing interface
<?php
interface Logger {
public function log(string $message): void;
}
$logger = new class implements Logger {
public function log(string $message): void {
echo "[LOG] $message\n";
}
};
$logger->log("Application started");
?>
In arrays
<?php
$handlers = [
'success' => new class {
public function handle(): void {
echo "Success!\n";
}
},
'error' => new class {
public function handle(): void {
echo "Error!\n";
}
},
];
$handlers['success']->handle();
?>
Mini Practice
Write PHP code that:
- Creates an anonymous class
- Passes constructor arguments
- Implements an interface
- Uses anonymous classes in arrays
Up Next
In the next lesson, you'll learn about Enums — enumerations in PHP 8.1+.
Related Topics
Frequently Asked Questions about Classes and Objects
What is Classes and Objects in PHP?
Classes and Objects is a fundamental concept in PHP. This lesson explains it step by step with clear examples, making it easy for beginners to understand.
How do I learn Classes and Objects?
Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Classes and Objects.
Why is Classes and Objects important in PHP?
Classes and Objects is essential for PHP development. Understanding this concept will help you write better code and solve real-world problems more effectively.