Bird
Raised Fist0
PHPprogramming~20 mins

Why design patterns matter in PHP - Challenge Your Understanding

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Design Patterns Mastery
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 Singleton pattern example?

Consider this PHP code implementing a Singleton pattern. What will it output?

PHP
<?php
class Singleton {
    private static ?Singleton $instance = null;
    public int $value;

    private function __construct() {
        $this->value = rand(1, 100);
    }

    public static function getInstance(): Singleton {
        if (self::$instance === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
}

$a = Singleton::getInstance();
$b = Singleton::getInstance();
echo $a->value . ',' . $b->value;
?>
ASame random number printed twice separated by a comma
BTwo different random numbers separated by a comma
CSyntax error due to nullable type declaration
DFatal error: Cannot access private constructor
Attempts:
2 left
💡 Hint

Singleton ensures only one instance exists.

🧠 Conceptual
intermediate
1:30remaining
Why use design patterns in software development?

Which of the following best explains why design patterns matter?

AThey offer proven solutions to common problems, improving code quality and communication
BThey guarantee software will have no bugs
CThey provide ready-made code that can be copied without understanding
DThey force developers to write more complex code to impress others
Attempts:
2 left
💡 Hint

Think about how patterns help teams work together and avoid reinventing the wheel.

🔧 Debug
advanced
2:00remaining
What error does this Factory pattern code produce?

Examine this PHP code snippet using a Factory pattern. What error will it raise when run?

PHP
<?php
interface Product {
    public function getName(): string;
}

class ProductA implements Product {
    public function getName(): string {
        return 'Product A';
    }
}

class ProductFactory {
    public static function create(string $type): Product {
        if ($type === 'A') {
            return new ProductA();
        } elseif ($type === 'B') {
            return new ProductB();
        }
        throw new Exception('Unknown product type');
    }
}

$product = ProductFactory::create('B');
echo $product->getName();
?>
AException: Unknown product type
BFatal error: Class 'ProductB' not found
CSyntax error: missing semicolon
DOutput: Product B
Attempts:
2 left
💡 Hint

Check if all classes used are defined.

📝 Syntax
advanced
2:30remaining
Which option correctly implements the Observer pattern in PHP?

Which of the following PHP code snippets correctly implements the Observer pattern?

A
&lt;?php
interface Observer {
    public function update();
}

class Subject {
    private array $observers = [];

    public function attach(Observer $observer) {
        $this-&gt;observers[] = $observer;
    }

    public function notify() {
        foreach ($this-&gt;observers as $observer) {
            $observer-&gt;update('Hello');
        }
    }
}
?&gt;
B
&lt;?php
class Subject {
    private array $observers;

    public function attach(Observer $observer) {
        $this-&gt;observers-&gt;add($observer);
    }

    public function notify(string $message) {
        foreach ($this-&gt;observers as $observer) {
            $observer-&gt;update($message);
        }
    }
}
?&gt;
C
&lt;?php
interface Observer {
    public function update(string $message);
}

class Subject {
    private array $observers = [];

    public function attach(Observer $observer) {
        $this-&gt;observers[] = $observer;
    }

    public function notify() {
        foreach ($this-&gt;observers as $observer) {
            $observer-&gt;update();
        }
    }
}
?&gt;
D
&lt;?php
interface Observer {
    public function update(string $message);
}

class Subject {
    private array $observers = [];

    public function attach(Observer $observer) {
        $this-&gt;observers[] = $observer;
    }

    public function notify(string $message) {
        foreach ($this-&gt;observers as $observer) {
            $observer-&gt;update($message);
        }
    }
}
?&gt;
Attempts:
2 left
💡 Hint

Check method signatures and how observers are stored and notified.

🚀 Application
expert
3:00remaining
How many objects are created in this Decorator pattern example?

Given this PHP code using the Decorator pattern, how many objects are created in total?

PHP
<?php
interface Coffee {
    public function cost(): float;
}

class SimpleCoffee implements Coffee {
    public function cost(): float {
        return 5.0;
    }
}

class MilkDecorator implements Coffee {
    private Coffee $coffee;

    public function __construct(Coffee $coffee) {
        $this->coffee = $coffee;
    }

    public function cost(): float {
        return $this->coffee->cost() + 1.5;
    }
}

class SugarDecorator implements Coffee {
    private Coffee $coffee;

    public function __construct(Coffee $coffee) {
        $this->coffee = $coffee;
    }

    public function cost(): float {
        return $this->coffee->cost() + 0.5;
    }
}

$coffee = new SugarDecorator(new MilkDecorator(new SimpleCoffee()));
echo $coffee->cost();
?>
A2 objects
B1 object
C3 objects
D4 objects
Attempts:
2 left
💡 Hint

Count each new keyword creating an object.

Practice

(1/5)
1. Why are design patterns important in PHP programming?
easy
A. They provide proven solutions to common coding problems.
B. They make the code run faster automatically.
C. They replace the need for comments in code.
D. They allow PHP to connect directly to databases.

Solution

  1. Step 1: Understand the purpose of design patterns

    Design patterns are reusable solutions to common problems in software design.
  2. Step 2: Identify the benefit in PHP context

    They help programmers write code that is easier to understand and maintain.
  3. Final Answer:

    They provide proven solutions to common coding problems. -> Option A
  4. Quick Check:

    Design patterns = proven solutions [OK]
Hint: Design patterns solve common problems clearly [OK]
Common Mistakes:
  • Thinking design patterns improve speed automatically
  • Believing design patterns remove need for comments
  • Confusing design patterns with database connections
2. Which of the following is the correct way to describe a design pattern in PHP?
easy
A. A specific function that runs faster than others.
B. A reusable template for solving common design problems.
C. A PHP extension for database access.
D. A tool to automatically generate PHP code.

Solution

  1. Step 1: Define design pattern

    A design pattern is a general reusable solution, not a specific function or tool.
  2. Step 2: Match the correct description

    A reusable template for solving common design problems. correctly describes it as a reusable template for design problems.
  3. Final Answer:

    A reusable template for solving common design problems. -> Option B
  4. Quick Check:

    Design pattern = reusable template [OK]
Hint: Design patterns are templates, not functions or tools [OK]
Common Mistakes:
  • Confusing design patterns with PHP functions
  • Thinking design patterns are PHP extensions
  • Believing design patterns generate code automatically
3. What will be the output of this PHP code snippet?
<?php
class Singleton {
  private static $instance = null;
  private function __construct() {}
  public static function getInstance() {
    if (self::$instance === null) {
      self::$instance = new Singleton();
    }
    return self::$instance;
  }
}
$a = Singleton::getInstance();
$b = Singleton::getInstance();
var_dump($a === $b);
?>
medium
A. bool(false)
B. Error: Cannot access private constructor
C. bool(true)
D. NULL

Solution

  1. Step 1: Understand Singleton pattern behavior

    The Singleton pattern ensures only one instance exists by storing it in a static variable.
  2. Step 2: Compare instances $a and $b

    Both $a and $b get the same instance from getInstance(), so they are identical.
  3. Final Answer:

    bool(true) -> Option C
  4. Quick Check:

    Singleton instances equal = bool(true) [OK]
Hint: Singleton returns same instance always [OK]
Common Mistakes:
  • Assuming different instances are created each call
  • Expecting an error from private constructor
  • Confusing output with NULL or false
4. Identify the error in this PHP code using a design pattern:
<?php
class Logger {
  private static $instance;
  private function __construct() {}
  public static function getInstance() {
    if (!self::$instance) {
      return new Logger();
    }
    return self::$instance;
  }
}
$log1 = Logger::getInstance();
$log2 = Logger::getInstance();
var_dump($log1 === $log2);
?>
medium
A. getInstance() does not assign the new instance to static property.
B. The constructor should be public.
C. Static property should be non-static.
D. Logger class should not have a constructor.

Solution

  1. Step 1: Check getInstance() logic

    The method creates a new Logger but does not save it to self::$instance.
  2. Step 2: Understand consequence

    Each call returns a new object, so $log1 and $log2 are different.
  3. Final Answer:

    getInstance() does not assign the new instance to static property. -> Option A
  4. Quick Check:

    Missing assignment causes multiple instances [OK]
Hint: Assign new instance to static property in getInstance() [OK]
Common Mistakes:
  • Making constructor public mistakenly
  • Changing static property to non-static
  • Removing constructor unnecessarily
5. You want to ensure your PHP team writes code that is easy to maintain and reuse. Which design pattern practice helps achieve this best?
hard
A. Writing all code in one big file for simplicity.
B. Using random code styles to encourage creativity.
C. Avoiding design patterns to keep code flexible.
D. Using design patterns to provide clear, reusable solutions.

Solution

  1. Step 1: Identify goal for maintainability and reuse

    Clear, reusable code is easier to maintain and share among team members.
  2. Step 2: Match design pattern practice

    Design patterns provide proven templates that improve code clarity and reuse.
  3. Final Answer:

    Using design patterns to provide clear, reusable solutions. -> Option D
  4. Quick Check:

    Design patterns improve maintainability and reuse [OK]
Hint: Design patterns improve teamwork and code reuse [OK]
Common Mistakes:
  • Thinking one big file is simpler
  • Avoiding patterns reduces code quality
  • Using inconsistent styles harms teamwork
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