📖 Scenario: Imagine you are creating a simple PHP class to represent a Book in a library system. You want to set the book's title and author when you create the book object, and you want to display a message when the book object is removed from memory.
🎯 Goal: Build a PHP class called Book that uses __construct to set the title and author when a new book is created, and uses __destruct to print a message when the book object is destroyed.
📋 What You'll Learn
Create a class named Book with two properties: title and author.
Add a __construct method that takes two parameters: $title and $author, and sets the class properties.
Add a __destruct method that prints: "Destroying book: [title] by [author]".
Create an instance of Book with title "1984" and author "George Orwell".
Print the book's title and author after creating the object.
💡 Why This Matters
🌍 Real World
Constructors and destructors help manage resources and setup/cleanup tasks automatically when objects are created and destroyed, useful in many PHP applications like web development.
💼 Career
Understanding these magic methods is important for PHP developers to write clean, efficient, and maintainable object-oriented code.
Progress0 / 4 steps
1
Create the Book class with properties
Create a PHP class called Book with two public properties: $title and $author.
PHP
Hint
Use class Book { public string $title; public string $author; } to define the class and properties.
2
Add the __construct method
Add a __construct method inside the Book class that takes two parameters: $title and $author. Inside the method, set the class properties $this->title and $this->author to these parameters.
PHP
Hint
Define public function __construct(string $title, string $author) and assign parameters to properties.
3
Add the __destruct method
Add a __destruct method inside the Book class that prints the message: "Destroying book: [title] by [author]" using echo. Use $this->title and $this->author to insert the values.
PHP
Hint
Use public function __destruct() and inside it use echo with the message including $this->title and $this->author.
4
Create a Book object and print its details
Create a new Book object called $book with title "1984" and author "George Orwell". Then print the book's title and author in the format: "Title: 1984, Author: George Orwell" using echo.
PHP
Hint
Create the object with new Book("1984", "George Orwell") and print the details with echo.
Practice
(1/5)
1. What is the main purpose of the __construct method in a PHP class?
easy
A. To pause the program execution
B. To delete an object from memory
C. To print the object details
D. To initialize an object when it is created
Solution
Step 1: Understand the role of __construct
The __construct method is automatically called when a new object is created from a class.
Step 2: Identify its purpose
It is used to set up or initialize the object, like setting initial values or preparing resources.
Final Answer:
To initialize an object when it is created -> Option D
Quick Check:
__construct = initialize object [OK]
Hint: Constructor runs at object creation to set it up [OK]
Common Mistakes:
Confusing __construct with __destruct
Thinking __construct deletes objects
Assuming __construct prints output
2. Which of the following is the correct syntax to define a destructor method in a PHP class?
easy
A. function __destruct() {}
B. function destruct() {}
C. function __delete() {}
D. function destructor() {}
Solution
Step 1: Recall PHP destructor syntax
PHP uses the special method named __destruct with two underscores to define destructors.
Step 2: Match the correct syntax
The correct syntax is function __destruct() {}. Other options are invalid method names for destructors.
Final Answer:
function __destruct() {} -> Option A
Quick Check:
Destructor syntax = __destruct() [OK]
Hint: Destructor method always named __destruct() with double underscores [OK]
Common Mistakes:
Using single underscore or wrong method name
Forgetting parentheses in method definition
Confusing destructor with constructor syntax
3. What will be the output of the following PHP code?
class Test {
function __construct() {
echo "Start ";
}
function __destruct() {
echo "End";
}
}
$obj = new Test();
echo "Middle ";
medium
A. Middle Start End
B. Start End Middle
C. Start Middle End
D. End Start Middle
Solution
Step 1: Trace constructor execution
When $obj = new Test(); runs, __construct prints "Start ".
Step 2: Trace echo after object creation
Next, echo "Middle "; prints "Middle ".
Step 3: Understand destructor timing
Destructor __destruct runs when script ends or object is destroyed, printing "End" last.
Final Answer:
Start Middle End -> Option C
Quick Check:
Constructor -> echo -> Destructor = Start Middle End [OK]
Hint: Constructor prints first, destructor last after script ends [OK]
Common Mistakes:
Assuming destructor runs immediately after constructor
Mixing order of printed words
Forgetting destructor runs at script end
4. Identify the error in this PHP class code:
class Sample {
function __construct {
echo "Hello";
}
function __destruct() {
echo "Goodbye";
}
}
$obj = new Sample();
medium
A. Destructor method name is incorrect
B. Missing parentheses in __construct method definition
C. Class name must be capitalized
D. Missing semicolon after echo statements
Solution
Step 1: Check constructor syntax
The __construct method is missing parentheses () after its name, which is required in PHP.
Step 2: Verify other parts
The destructor name and syntax are correct, class name capitalization is not mandatory, and echo statements have semicolons.
Final Answer:
Missing parentheses in __construct method definition -> Option B
Quick Check:
Constructor needs () after name [OK]
Hint: Always add () after method names, even if no parameters [OK]
Common Mistakes:
Omitting parentheses in method definitions
Thinking destructor name is wrong
Believing class names must be capitalized
5. You want to create a PHP class that opens a file when an object is created and closes it automatically when the object is destroyed. Which code snippet correctly uses __construct and __destruct for this purpose?
hard
A. class FileHandler {
private $file;
function __construct($filename) {
$this->file = fopen($filename, 'r');
}
function __destruct() {
fclose($this->file);
}
}
B. class FileHandler {
private $file;
function __construct() {
fclose($this->file);
}
function __destruct() {
$this->file = fopen('file.txt', 'r');
}
}
C. class FileHandler {
function __construct($filename) {
fclose($filename);
}
function __destruct() {
fopen($filename, 'r');
}
}
D. class FileHandler {
private $file;
function __construct($filename) {
$this->file = fopen($filename, 'r');
}
function __destruct() {
echo 'File closed';
}
}
Solution
Step 1: Analyze constructor for opening file
class FileHandler {
private $file;
function __construct($filename) {
$this->file = fopen($filename, 'r');
}
function __destruct() {
fclose($this->file);
}
} correctly opens the file with fopen and stores the handle in $this->file.
Step 2: Analyze destructor for closing file
class FileHandler {
private $file;
function __construct($filename) {
$this->file = fopen($filename, 'r');
}
function __destruct() {
fclose($this->file);
}
} correctly closes the file using fclose($this->file) in the destructor, ensuring cleanup.
Step 3: Check other options for errors
class FileHandler {
private $file;
function __construct() {
fclose($this->file);
}
function __destruct() {
$this->file = fopen('file.txt', 'r');
}
} reverses open/close actions. class FileHandler {
function __construct($filename) {
fclose($filename);
}
function __destruct() {
fopen($filename, 'r');
}
} misuses fclose and fopen with wrong variables. class FileHandler {
private $file;
function __construct($filename) {
$this->file = fopen($filename, 'r');
}
function __destruct() {
echo 'File closed';
}
} does not close the file, only prints a message.
Final Answer:
class FileHandler {
private $file;
function __construct($filename) {
$this->file = fopen($filename, 'r');
}
function __destruct() {
fclose($this->file);
}
} -> Option A
Quick Check:
Open in __construct, close in __destruct = class FileHandler {
private $file;
function __construct($filename) {
$this->file = fopen($filename, 'r');
}
function __destruct() {
fclose($this->file);
}
} [OK]
Hint: Open resource in constructor, close it in destructor [OK]
Common Mistakes:
Closing file in constructor or opening in destructor
Not storing file handle in a property
Only printing message instead of closing resource
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.