0
0
PHPprogramming~5 mins

Destructor method in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a destructor method in PHP?
A destructor method is a special function in a PHP class that runs automatically when an object is destroyed or goes out of scope. It is used to clean up resources like closing files or database connections.
Click to reveal answer
beginner
How do you name a destructor method in PHP?
In PHP, the destructor method is named __destruct() with two underscores at the start. It does not take any parameters.
Click to reveal answer
beginner
When is the destructor method called in PHP?
The destructor method is called automatically when the object is no longer needed, such as when the script ends, the object is unset, or it goes out of scope.
Click to reveal answer
beginner
What is a common use case for a destructor method?
A common use case is to release resources like closing database connections, freeing memory, or saving data before the object is destroyed.
Click to reveal answer
beginner
Write a simple PHP class with a destructor that prints a message when the object is destroyed.
Example:<br><pre>&lt;?php
class MyClass {
  public function __destruct() {
    echo "Object destroyed!";
  }
}
$obj = new MyClass();
// When script ends or object is unset, it prints: Object destroyed!
?&gt;</pre>
Click to reveal answer
What is the correct name of the destructor method in PHP?
A__destruct()
Bdestruct()
C__destroy()
Ddelete()
When is the destructor method called automatically?
AWhen a method is called
BWhen the object is created
CWhen the object is destroyed or goes out of scope
DWhen a variable is assigned
Which of these is a common use for a destructor?
ACreating a new object
BReading user input
CStarting a session
DClosing a database connection
Can the destructor method take parameters in PHP?
ANo, it cannot take parameters
BYes, it can take any number of parameters
CYes, but only one parameter
DOnly optional parameters
What happens if you unset an object in PHP?
AThe object is copied
BThe destructor method is called
CNothing happens
DThe constructor method is called
Explain what a destructor method is and when it is used in PHP.
Think about what happens when an object is no longer needed.
You got /4 concepts.
    Write a simple PHP class with a destructor that outputs a message when the object is destroyed.
    Use __destruct() and echo inside it.
    You got /4 concepts.