Bird
Raised Fist0
PHPprogramming~20 mins

Factory pattern in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Factory Pattern Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this PHP factory pattern code?

Consider the following PHP code using a simple factory pattern. What will it print?

PHP
<?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();
}
?>
AMeow!
BWoof!
CUnknown animal type
DFatal error
Attempts:
2 left
💡 Hint

Look at which animal type is passed to the factory and what speak() returns for that animal.

❓ Predict Output
intermediate
2:00remaining
What happens if an unknown type is passed to the factory?

What will be the output of this PHP code when the factory is called with 'bird'?

PHP
<?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();
}
?>
AUnknown animal type
BMeow!
CWoof!
DFatal error
Attempts:
2 left
💡 Hint

Check what the factory does when the type is not 'dog' or 'cat'.

🔧 Debug
advanced
2:00remaining
Why does this factory code cause a fatal error?

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
<?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();
?>
ASyntax error: missing semicolon
BOutputs 'Woof!'
CFatal error: Uncaught Error: Call to a member function speak() on null
DException thrown: Unknown animal type
Attempts:
2 left
💡 Hint

What happens if the factory method does not return anything?

🧠 Conceptual
advanced
2:00remaining
What is the main benefit of using the factory pattern here?

Given the PHP factory pattern example creating different Animal objects, what is the main advantage of using this pattern?

AIt prevents any exceptions from being thrown
BIt makes the code run faster by avoiding object creation
CIt forces all animals to have the same speak() output
DIt hides the creation logic and allows easy addition of new animal types without changing client code
Attempts:
2 left
💡 Hint

Think about how the client code uses the factory and what changes if new animals are added.

📝 Syntax
expert
2:00remaining
Which option correctly implements a PHP factory method with typed return and exception handling?

Choose the correct PHP factory method code that returns an Animal instance or throws an Exception for unknown types.

A
public static function create(string $type): Animal {
    if ($type === 'dog') return new Dog();
    elseif ($type === 'cat') return new Cat();
    else throw new Exception('Unknown type');
}
B
public static function create(string $type): Animal {
    if ($type === 'dog') return new Dog();
    elseif ($type === 'cat') return new Cat();
    else return 'Unknown type';
}
C
public static function create(string $type) {
    if ($type === 'dog') return new Dog();
    elseif ($type === 'cat') return new Cat();
    else throw new Exception('Unknown type');
}
D
public static function create(string $type): Animal {
    switch ($type) {
        case 'dog': return new Dog();
        case 'cat': return new Cat();
        default: echo 'Unknown type';
    }
}
Attempts:
2 left
💡 Hint

Check the return type and how unknown types are handled.

Practice

(1/5)
1. What is the main purpose of the Factory Pattern in PHP?
easy
A. To create objects without exposing the creation logic to the client
B. To store data in a database
C. To handle user input validation
D. To perform mathematical calculations

Solution

  1. Step 1: Understand the role of the Factory Pattern

    The Factory Pattern is designed to create objects while hiding the details of how they are created.
  2. Step 2: Compare options with the pattern's purpose

    Only To create objects without exposing the creation logic to the client describes creating objects without exposing creation logic, which matches the Factory Pattern.
  3. Final Answer:

    To create objects without exposing the creation logic to the client -> Option A
  4. Quick Check:

    Factory Pattern = Object creation hiding [OK]
Hint: Factory pattern hides object creation details [OK]
Common Mistakes:
  • Confusing factory pattern with database operations
  • Thinking it handles input validation
  • Assuming it performs calculations
2. Which of the following is the correct way to define a factory method in PHP?
easy
A. public static function create() {}
B. function create() {}
C. public function create() {}
D. private function create() {}

Solution

  1. Step 1: Identify typical factory method signature

    Factory methods are often static so they can be called without creating an instance.
  2. Step 2: Check options for static keyword

    Only public static function create() {} uses public static function create(), which is the common factory method style.
  3. Final Answer:

    public static function create() {} -> Option A
  4. Quick Check:

    Factory method is usually static [OK]
Hint: Factory methods are usually static for easy access [OK]
Common Mistakes:
  • Omitting static keyword for factory methods
  • Using private visibility which blocks access
  • Not specifying visibility (defaults to public but less clear)
3. What will be the output of the following PHP code?
class Book { }
class ProductFactory {
public static function create($type) {
if ($type === 'Book') {
return new Book();
}
return null;
}
}
$product = ProductFactory::create('Book');
echo get_class($product);
medium
A. null
B. ProductFactory
C. Book
D. Error: Class not found

Solution

  1. Step 1: Analyze the factory method call

    The call ProductFactory::create('Book') checks if the type is 'Book' and returns a new Book object.
  2. Step 2: Check the output of get_class

    Since the returned object is an instance of Book, get_class($product) returns "Book".
  3. Final Answer:

    Book -> Option C
  4. Quick Check:

    Factory returns Book object, get_class = Book [OK]
Hint: Factory returns object; get_class shows its class name [OK]
Common Mistakes:
  • Expecting factory class name instead of product class
  • Assuming null is returned
  • Thinking code throws error due to missing class
4. Identify the error in this factory pattern implementation:
class Car {}
class VehicleFactory {
public static function create($type) {
if ($type = 'Car') {
return new Car();
}
return null;
}
}
medium
A. Missing return type declaration
B. Using assignment (=) instead of comparison (==) in the if condition
C. Class Car is not defined
D. Factory method should not be static

Solution

  1. Step 1: Check the if condition syntax

    The condition uses = which assigns 'Car' to $type instead of comparing it.
  2. Step 2: Understand impact of assignment in condition

    Assignment always returns true, so the if block always runs regardless of input, which is a logic error.
  3. Final Answer:

    Using assignment (=) instead of comparison (==) in the if condition -> Option B
  4. Quick Check:

    Use == for comparison, not = [OK]
Hint: Use == for comparison, not = assignment in conditions [OK]
Common Mistakes:
  • Confusing = and == in if statements
  • Thinking static method is wrong here
  • Assuming missing return type causes error
5. You want to extend a factory to create different types of vehicles: Car, Bike, and Truck. Which approach best follows the Factory Pattern principles in PHP?
hard
A. Create separate factory classes for CarFactory, BikeFactory, and TruckFactory each with their own create method
B. Use global functions to create Car, Bike, and Truck objects directly
C. Create one class Vehicle with properties to switch between Car, Bike, and Truck behaviors
D. Create a VehicleFactory with a static create method that returns new Car, Bike, or Truck objects based on input

Solution

  1. Step 1: Understand the Factory Pattern goal

    The pattern centralizes object creation in one place, hiding details from the client.
  2. Step 2: Evaluate options for best factory design

    Create a VehicleFactory with a static create method that returns new Car, Bike, or Truck objects based on input uses one factory class with a method that creates different vehicle objects based on input, which is the classic factory pattern.
  3. Step 3: Compare other options

    Create separate factory classes for CarFactory, BikeFactory, and TruckFactory each with their own create method splits factories, which is more like Abstract Factory or multiple factories, not simple Factory Pattern. Create one class Vehicle with properties to switch between Car, Bike, and Truck behaviors mixes behaviors in one class, breaking single responsibility. Use global functions to create Car, Bike, and Truck objects directly uses global functions, which is not object-oriented.
  4. Final Answer:

    Create a VehicleFactory with a static create method that returns new Car, Bike, or Truck objects based on input -> Option D
  5. Quick Check:

    Single factory method creates varied objects [OK]
Hint: One factory method returns different objects by input [OK]
Common Mistakes:
  • Splitting factories unnecessarily
  • Mixing multiple behaviors in one class
  • Using global functions instead of classes
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard