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?✗ Incorrect
The
new keyword creates a new object and automatically calls the __construct method.When is the
__destruct method called?✗ Incorrect
The
__destruct method runs when the object is destroyed or the script finishes.Can a PHP class have more than one
__construct method?✗ Incorrect
PHP allows only one
__construct method per class.What is a common use of the
__destruct method?✗ Incorrect
__destruct is used to clean up resources before the object is removed.Which of these is true about
__construct?✗ Incorrect
__construct runs automatically right after an object is created.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.