0
0
PHPprogramming~10 mins

Destructor method 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 define a destructor method in a PHP class.

PHP
<?php
class Sample {
    public function [1]() {
        echo "Destructor called";
    }
}
?>
Drag options to blanks, or click blank then click option'
Adelete
B__construct
C__destruct
Ddestruct
Attempts:
3 left
💡 Hint
Common Mistakes
Using __construct instead of __destruct
Omitting the double underscores
Naming the method destruct without underscores
2fill in blank
medium

Complete the code to call the destructor automatically when the object is destroyed.

PHP
<?php
class Logger {
    public function __destruct() {
        echo "Closing log file.";
    }
}
$log = new Logger();
[1];
Drag options to blanks, or click blank then click option'
Aunset($log)
Bdelete $log
Cdestroy($log)
Dremove($log)
Attempts:
3 left
💡 Hint
Common Mistakes
Using delete which is not a PHP keyword
Using destroy or remove which do not exist in PHP
3fill in blank
hard

Fix the error in the destructor method name to ensure it is called properly.

PHP
<?php
class FileHandler {
    public function [1]() {
        echo "File closed.";
    }
}
?>
Drag options to blanks, or click blank then click option'
Adestruct
B__destruct
C__destructor
Ddelete
Attempts:
3 left
💡 Hint
Common Mistakes
Using __destructor instead of __destruct
Omitting underscores
Using unrelated names like delete
4fill in blank
hard

Fill both blanks to create a class with a destructor that outputs a message when the object is destroyed.

PHP
<?php
class UserSession {
    public function [1]() {
        echo "Session ended.";
    }
}
$session = new UserSession();
[2]($session);
Drag options to blanks, or click blank then click option'
A__destruct
Bunset
Cdelete
D__construct
Attempts:
3 left
💡 Hint
Common Mistakes
Using __construct instead of __destruct
Using delete which is not a PHP function
5fill in blank
hard

Fill all three blanks to define a class with a destructor that frees a resource and outputs a message when the object is destroyed.

PHP
<?php
class DatabaseConnection {
    private $conn;
    public function __construct() {
        $this->conn = "Connected";
    }
    public function [1]() {
        $this->conn = null;
        echo [2];
    }
}
$db = new DatabaseConnection();
[3]($db);
Drag options to blanks, or click blank then click option'
A__destruct
Bunset
C"Connection closed."
D__construct
Attempts:
3 left
💡 Hint
Common Mistakes
Using __construct instead of __destruct
Not using quotes around the message
Using delete instead of unset