0
0
PHPprogramming~20 mins

Factory pattern in PHP - Practice Problems & Coding Challenges

Choose your learning style9 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.