How can a factory method be used to instantiate different derived classes based on a type in PHP?
To instantiate different derived classes based on a type in PHP using a factory method, we can create a factory class with a method that takes a type parameter and returns an instance of the appropriate derived class based on that type. This allows for flexibility in creating objects without exposing the instantiation logic to the client code.
```php
<?php
// Base class
abstract class Shape {
abstract public function draw();
}
// Derived classes
class Circle extends Shape {
public function draw() {
echo "Drawing a circle\n";
}
}
class Square extends Shape {
public function draw() {
echo "Drawing a square\n";
}
}
// Factory class
class ShapeFactory {
public static function createShape($type) {
switch ($type) {
case 'circle':
return new Circle();
case 'square':
return new Square();
default:
return null;
}
}
}
// Client code
$circle = ShapeFactory::createShape('circle');
$circle->draw();
$square = ShapeFactory::createShape('square');
$square->draw();
```
This code snippet demonstrates how a factory method can be used to instantiate different derived classes based on a type in PHP.
Keywords
Related Questions
- In the context of PHP code generating a download link, what steps can be taken to ensure that the browser correctly identifies the file type and prompts the user to open or save the file instead of displaying gibberish characters?
- In what scenarios is SQLite a suitable alternative when a traditional database is not available for PHP development?
- What is the purpose of the script mentioned in the forum thread?