0
0
PHPprogramming~5 mins

__construct and __destruct in PHP - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the __construct method in PHP classes?
The <code>__construct</code> method is a special function called automatically when a new object of a class is created. It is used to initialize the object's properties or run setup code.
Click to reveal answer
beginner
What does the __destruct method do in a PHP class?
The __destruct method is called automatically when an object is destroyed or the script ends. It is used to clean up resources like closing files or database connections.
Click to reveal answer
beginner
When exactly is the __construct method called?
It is called right after an object is created with the new keyword, before any other methods are used on the object.
Click to reveal answer
intermediate
Can a PHP class have multiple <code>__construct</code> methods?
No, a PHP class can only have one <code>__construct</code> method. To handle different ways of creating objects, you can use optional parameters or method overloading techniques.
Click to reveal answer
beginner
Give a simple example of a PHP class using <code>__construct</code> and <code>__destruct</code>.
Example:<br><pre>class Car {
  public function __construct() {
    echo "Car created!\n";
  }
  public function __destruct() {
    echo "Car destroyed!\n";
  }
}
$myCar = new Car();</pre>
Click to reveal answer
What keyword triggers the __construct method in PHP?
Acreate
Bstart
Cinit
Dnew
When is the __destruct method called?
AWhen the object is created
BWhen the object is destroyed or script ends
CWhen a method is called
DWhen a property is accessed
Can a PHP class have more than one __construct method?
ANo, only one constructor is allowed
BYes, multiple constructors are allowed
CYes, but only if they have different names
DNo, constructors are not allowed
What is a common use of the __destruct method?
ATo initialize object properties
BTo create new objects
CTo clean up resources like files or connections
DTo print messages when object is created
Which of these is true about __construct?
AIt runs automatically after object creation
BIt runs only when called explicitly
CIt runs when the object is destroyed
DIt runs before the class is defined
Explain in your own words what __construct and __destruct methods do in PHP classes.
Think about what happens when you get a new item and when you throw it away.
You got /4 concepts.
    Describe a simple real-life example where you might use both __construct and __destruct in a PHP class.
    Imagine borrowing a book and returning it.
    You got /3 concepts.