Consider the following PHP code using a simple factory pattern. What will it print?
<?php interface Animal { public function speak(); } class Dog implements Animal { public function speak() { return "Woof!"; } } class Cat implements Animal { public function speak() { return "Meow!"; } } class AnimalFactory { public static function createAnimal(string $type): Animal { return match($type) { 'dog' => new Dog(), 'cat' => new Cat(), default => throw new Exception("Unknown animal type"), }; } } try { $animal = AnimalFactory::createAnimal('dog'); echo $animal->speak(); } catch (Exception $e) { echo $e->getMessage(); } ?>
Look at which animal type is passed to the factory and what speak() returns for that animal.
The factory creates a Dog object because 'dog' is passed. Dog's speak() returns "Woof!" so that is printed.
What will be the output of this PHP code when the factory is called with 'bird'?
<?php interface Animal { public function speak(); } class Dog implements Animal { public function speak() { return "Woof!"; } } class Cat implements Animal { public function speak() { return "Meow!"; } } class AnimalFactory { public static function createAnimal(string $type): Animal { return match($type) { 'dog' => new Dog(), 'cat' => new Cat(), default => throw new Exception("Unknown animal type"), }; } } try { $animal = AnimalFactory::createAnimal('bird'); echo $animal->speak(); } catch (Exception $e) { echo $e->getMessage(); } ?>
Check what the factory does when the type is not 'dog' or 'cat'.
The factory throws an Exception with message "Unknown animal type" when the type is not recognized. The catch block prints this message.
Look at this PHP code snippet. It tries to create an animal using the factory but causes a fatal error. What is the cause?
<?php interface Animal { public function speak(); } class Dog implements Animal { public function speak() { return "Woof!"; } } class AnimalFactory { public static function createAnimal(string $type) { if ($type == 'dog') { return new Dog(); } // Missing return for other types } } $animal = AnimalFactory::createAnimal('cat'); echo $animal->speak(); ?>
What happens if the factory method does not return anything?
If the factory method returns nothing (null), then $animal is null. Calling speak() on null causes a fatal error.
Given the PHP factory pattern example creating different Animal objects, what is the main advantage of using this pattern?
Think about how the client code uses the factory and what changes if new animals are added.
The factory pattern hides the creation details and lets you add new animal classes without modifying the code that uses them.
Choose the correct PHP factory method code that returns an Animal instance or throws an Exception for unknown types.
Check the return type and how unknown types are handled.
Option A correctly declares the return type Animal and throws an Exception for unknown types. Others either return wrong types or do not declare return type.