0
0
PHPprogramming~10 mins

Singleton pattern in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare the Singleton class property.

PHP
<?php
class Singleton {
    private static [1];
}
Drag options to blanks, or click blank then click option'
A$unique
B$object
C$single
D$instance
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-static property for the instance.
Naming the property something other than $instance.
2fill in blank
medium

Complete the code to prevent creating multiple instances by making the constructor private.

PHP
<?php
class Singleton {
    private function [1]() {}
}
Drag options to blanks, or click blank then click option'
A__clone
B__destruct
C__construct
D__invoke
Attempts:
3 left
💡 Hint
Common Mistakes
Making the constructor public or protected.
Confusing constructor with clone or destructor.
3fill in blank
hard

Fix the error in the method that returns the single instance.

PHP
<?php
class Singleton {
    private static $instance;
    private function __construct() {}
    public static function getInstance() {
        if (self::[1] === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
}
Drag options to blanks, or click blank then click option'
A$instance
Binstance
C$Instance
DInstance
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting the dollar sign when accessing static property.
Using wrong case for the property name.
4fill in blank
hard

Fill both blanks to prevent cloning and unserializing the Singleton instance.

PHP
<?php
class Singleton {
    private function [1]() {}
    public function [2]() {
        throw new \Exception("Cannot clone singleton");
    }
}
Drag options to blanks, or click blank then click option'
A__wakeup
B__clone
C__sleep
D__destruct
Attempts:
3 left
💡 Hint
Common Mistakes
Not preventing cloning or unserializing.
Using wrong magic method names.
5fill in blank
hard

Fill all three blanks to complete the Singleton class with instance property, constructor, and getInstance method.

PHP
<?php
class Singleton {
    private static [1];
    private function [2]() {}
    public static function [3]() {
        if (self::$instance === null) {
            self::$instance = new Singleton();
        }
        return self::$instance;
    }
}
Drag options to blanks, or click blank then click option'
A$instance
B__construct
CgetInstance
D__clone
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong names for property or methods.
Making constructor public.