These special methods help set up and clean up objects automatically when you create or remove them.
__construct and __destruct in PHP
<?php class ClassName { public function __construct() { // code to run when object is created } public function __destruct() { // code to run when object is destroyed } } ?>
The __construct method runs automatically when you create a new object.
The __destruct method runs automatically when the object is removed or script ends.
<?php class Car { public function __construct() { echo "Car created!\n"; } public function __destruct() { echo "Car destroyed!\n"; } } $myCar = new Car(); ?>
<?php class Person { private string $name; public function __construct(string $name) { $this->name = $name; echo "Hello, $name!\n"; } public function __destruct() { echo "{$this->name} says goodbye!\n"; } } $person = new Person("Anna"); ?>
This program creates a Book object that announces when it opens and closes. The destructor runs automatically at the end.
<?php class Book { private string $title; public function __construct(string $title) { $this->title = $title; echo "Opening book: $title\n"; } public function __destruct() { echo "Closing book: {$this->title}\n"; } } $book = new Book("Learn PHP"); echo "Reading the book...\n"; // The destructor will run automatically at the end of the script ?>
You do not call __construct or __destruct yourself; PHP calls them automatically.
The destructor is useful for cleanup like closing files or database connections.
If you create multiple objects, each will run its own constructor and destructor.
__construct runs when an object is created to set it up.
__destruct runs when an object is removed to clean up.
They help automate starting and ending tasks for objects.
Practice
__construct method in a PHP class?Solution
Step 1: Understand the role of
The__construct__constructmethod 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 DQuick Check:
__construct= initialize object [OK]
- Confusing __construct with __destruct
- Thinking __construct deletes objects
- Assuming __construct prints output
Solution
Step 1: Recall PHP destructor syntax
PHP uses the special method named__destructwith two underscores to define destructors.Step 2: Match the correct syntax
The correct syntax isfunction __destruct() {}. Other options are invalid method names for destructors.Final Answer:
function __destruct() {} -> Option AQuick Check:
Destructor syntax = __destruct() [OK]
- Using single underscore or wrong method name
- Forgetting parentheses in method definition
- Confusing destructor with constructor syntax
class Test {
function __construct() {
echo "Start ";
}
function __destruct() {
echo "End";
}
}
$obj = new Test();
echo "Middle ";Solution
Step 1: Trace constructor execution
When$obj = new Test();runs,__constructprints "Start ".Step 2: Trace echo after object creation
Next,echo "Middle ";prints "Middle ".Step 3: Understand destructor timing
Destructor__destructruns when script ends or object is destroyed, printing "End" last.Final Answer:
Start Middle End -> Option CQuick Check:
Constructor -> echo -> Destructor = Start Middle End [OK]
- Assuming destructor runs immediately after constructor
- Mixing order of printed words
- Forgetting destructor runs at script end
class Sample {
function __construct {
echo "Hello";
}
function __destruct() {
echo "Goodbye";
}
}
$obj = new Sample();Solution
Step 1: Check constructor syntax
The__constructmethod 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 BQuick Check:
Constructor needs () after name [OK]
- Omitting parentheses in method definitions
- Thinking destructor name is wrong
- Believing class names must be capitalized
__construct and __destruct for this purpose?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 withfopenand 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 usingfclose($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'); } } misusesfcloseandfopenwith 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 AQuick 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]
- Closing file in constructor or opening in destructor
- Not storing file handle in a property
- Only printing message instead of closing resource
Ready to prove it?
Pass the test and this pattern moves unknown
