0
0
PHPprogramming~20 mins

Strategy pattern in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Strategy 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 Strategy pattern example?

Consider the following PHP code implementing a simple Strategy pattern for sorting an array. What will be the output when running this code?

PHP
<?php
interface SortStrategy {
    public function sort(array $data): array;
}

class BubbleSort implements SortStrategy {
    public function sort(array $data): array {
        $n = count($data);
        for ($i = 0; $i < $n; $i++) {
            for ($j = 0; $j < $n - $i - 1; $j++) {
                if ($data[$j] > $data[$j + 1]) {
                    $temp = $data[$j];
                    $data[$j] = $data[$j + 1];
                    $data[$j + 1] = $temp;
                }
            }
        }
        return $data;
    }
}

class ReverseSort implements SortStrategy {
    public function sort(array $data): array {
        rsort($data);
        return $data;
    }
}

class Sorter {
    private SortStrategy $strategy;

    public function __construct(SortStrategy $strategy) {
        $this->strategy = $strategy;
    }

    public function setStrategy(SortStrategy $strategy): void {
        $this->strategy = $strategy;
    }

    public function sort(array $data): array {
        return $this->strategy->sort($data);
    }
}

$data = [3, 1, 4, 1, 5];
$sorter = new Sorter(new BubbleSort());
$result1 = $sorter->sort($data);
$sorter->setStrategy(new ReverseSort());
$result2 = $sorter->sort($data);

print_r($result1);
print_r($result2);
?>
AArray ( [0] => 3 [1] => 1 [2] => 4 [3] => 1 [4] => 5 ) Array ( [0] => 3 [1] => 1 [2] => 4 [3] => 1 [4] => 5 )
BArray ( [0] => 5 [1] => 4 [2] => 3 [3] => 1 [4] => 1 ) Array ( [0] => 1 [1] => 1 [2] => 3 [3] => 4 [4] => 5 )
CFatal error: Uncaught Error: Call to undefined function rsort()
DArray ( [0] => 1 [1] => 1 [2] => 3 [3] => 4 [4] => 5 ) Array ( [0] => 5 [1] => 4 [2] => 3 [3] => 1 [4] => 1 )
Attempts:
2 left
💡 Hint

Think about what each strategy does to the array and the order of operations.

🧠 Conceptual
intermediate
1:30remaining
Why use the Strategy pattern?

Which of the following best explains the main benefit of using the Strategy pattern in PHP?

AIt allows changing the algorithm used by an object at runtime without modifying the object itself.
BIt forces all algorithms to be implemented in a single class for better performance.
CIt automatically generates code for different algorithms without manual coding.
DIt prevents any changes to the algorithm once the object is created.
Attempts:
2 left
💡 Hint

Think about flexibility and how the pattern helps with changing behavior.

🔧 Debug
advanced
2:30remaining
What error does this Strategy pattern code produce?

Examine the following PHP code snippet using the Strategy pattern. What error will it produce when run?

PHP
<?php
interface PaymentStrategy {
    public function pay(float $amount): string;
}

class CreditCardPayment implements PaymentStrategy {
    public function pay(float $amount): string {
        return "Paid $amount using credit card.";
    }
}

class PaypalPayment implements PaymentStrategy {
    public function pay(float $amount): string {
        return "Paid $amount using PayPal.";
    }
}

class PaymentContext {
    private PaymentStrategy $strategy;

    public function __construct(PaymentStrategy $strategy) {
        $this->strategy = $strategy;
    }

    public function setStrategy(PaymentStrategy $strategy): void {
        $this->strategy = $strategy;
    }

    public function pay(float $amount): string {
        return $this->strategy->pay($amount);
    }
}

$context = new PaymentContext(new CreditCardPayment());
echo $context->pay(100);
$context->setStrategy(new PaypalPayment());
echo $context->pay(50);
$context->setStrategy(new class implements PaymentStrategy {
    public function pay(float $amount): string {
        return "Paid $amount using Bitcoin.";
    }
});
echo $context->pay(25);
?>
AParse error: syntax error, unexpected 'class' (anonymous class syntax is invalid here)
BFatal error: Uncaught TypeError: Argument 1 passed to PaymentContext::setStrategy() must implement interface PaymentStrategy
COutput: Paid 100 using credit card.Paid 50 using PayPal.Paid 25 using Bitcoin.
DFatal error: Uncaught Error: Call to undefined method pay()
Attempts:
2 left
💡 Hint

Check the anonymous class passed to setStrategy and its relation to the interface.

📝 Syntax
advanced
1:30remaining
Which option correctly implements a Strategy interface in PHP?

Given the interface LoggerStrategy with method log(string $message): void, which option correctly implements this interface?

Aclass FileLogger implements LoggerStrategy { public function log(int $message): void { echo $message; } }
Bclass FileLogger implements LoggerStrategy { public function log(string $msg): void { file_put_contents('log.txt', $msg.PHP_EOL, FILE_APPEND); } }
Cclass FileLogger { public function log(string $message): void { echo $message; } }
Dclass FileLogger implements LoggerStrategy { public function log(string $message): string { return $message; } }
Attempts:
2 left
💡 Hint

Check method signatures and interface implementation rules.

🚀 Application
expert
2:30remaining
How many different strategies are used in this code?

Analyze the following PHP code using the Strategy pattern. How many distinct strategy classes are used to perform operations?

PHP
<?php
interface OperationStrategy {
    public function execute(int $a, int $b): int;
}

class AddOperation implements OperationStrategy {
    public function execute(int $a, int $b): int {
        return $a + $b;
    }
}

class MultiplyOperation implements OperationStrategy {
    public function execute(int $a, int $b): int {
        return $a * $b;
    }
}

class Calculator {
    private OperationStrategy $strategy;

    public function __construct(OperationStrategy $strategy) {
        $this->strategy = $strategy;
    }

    public function setStrategy(OperationStrategy $strategy): void {
        $this->strategy = $strategy;
    }

    public function calculate(int $a, int $b): int {
        return $this->strategy->execute($a, $b);
    }
}

$calc = new Calculator(new AddOperation());
$sum = $calc->calculate(5, 3);
$calc->setStrategy(new MultiplyOperation());
$product = $calc->calculate(5, 3);
$calc->setStrategy(new class implements OperationStrategy {
    public function execute(int $a, int $b): int {
        return $a - $b;
    }
});
$difference = $calc->calculate(5, 3);
A3
B2
C1
D4
Attempts:
2 left
💡 Hint

Count all classes implementing the OperationStrategy interface, including anonymous classes.