Consider this PHP code implementing a Singleton pattern. What will it output?
<?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; ?>
Singleton ensures only one instance exists.
The Singleton pattern creates only one instance. Both variables point to the same object, so their values are identical.
Which of the following best explains why design patterns matter?
Think about how patterns help teams work together and avoid reinventing the wheel.
Design patterns are reusable solutions that help developers solve common problems efficiently and communicate ideas clearly.
Examine this PHP code snippet using a Factory pattern. What error will it raise when run?
<?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(); ?>
Check if all classes used are defined.
The code tries to create an instance of ProductB, but this class is not defined, causing a fatal error.
Which of the following PHP code snippets correctly implements the Observer pattern?
Check method signatures and how observers are stored and notified.
Option D correctly defines the Observer interface with update(string $message), stores observers in an array, and calls update with the message.
Given this PHP code using the Decorator pattern, how many objects are created in total?
<?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(); ?>
Count each new keyword creating an object.
There are three objects: SimpleCoffee, MilkDecorator wrapping SimpleCoffee, and SugarDecorator wrapping MilkDecorator.