Bird
Raised Fist0
PHPprogramming~20 mins

__construct and __destruct in PHP - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
PHP Constructor & Destructor Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this PHP code with __construct and __destruct?

Consider the following PHP class with constructor and destructor methods. What will be printed when the script runs?

PHP
<?php
class Test {
    public function __construct() {
        echo "Start\n";
    }
    public function __destruct() {
        echo "End\n";
    }
}
$obj = new Test();
echo "Middle\n";
?>
A
Start
Middle
End
B
Start
End
Middle
C
Middle
Start
End
D
End
Start
Middle
Attempts:
2 left
💡 Hint

Remember that the constructor runs when the object is created, and the destructor runs when the script ends or the object is destroyed.

❓ Predict Output
intermediate
2:00remaining
What happens if __destruct modifies a property before script ends?

Look at this PHP code. What will be the output?

PHP
<?php
class Counter {
    public $count = 0;
    public function __construct() {
        $this->count = 1;
        echo "Construct: {$this->count}\n";
    }
    public function __destruct() {
        $this->count++;
        echo "Destruct: {$this->count}\n";
    }
}
$obj = new Counter();
echo "Count: {$obj->count}\n";
?>
A
Construct: 1
Count: 1
Destruct: 2
B
Construct: 1
Destruct: 2
Count: 1
C
Count: 0
Construct: 1
Destruct: 2
D
Construct: 1
Count: 2
Destruct: 3
Attempts:
2 left
💡 Hint

The destructor runs after the last output, so the property change is visible only inside the destructor.

🔧 Debug
advanced
2:00remaining
What error does this PHP code cause?

Examine this PHP class. What error will occur when running this code?

PHP
<?php
class Sample {
    public function __construct() {
        echo "Hello\n";
    }
}
$obj = new Sample();
?>
ANo error, outputs: Hello
BFatal error: Uncaught Error: Call to undefined method
CParse error: syntax error, unexpected '}'
DParse error: syntax error, unexpected end of file
Attempts:
2 left
💡 Hint

Check the syntax carefully, especially punctuation after statements.

🧠 Conceptual
advanced
1:30remaining
When is __destruct called in PHP?

Choose the correct statement about when the __destruct method is called in PHP.

A__destruct is called immediately after the constructor finishes.
B__destruct is called when the object is no longer referenced or script ends.
C__destruct is called before the constructor runs.
D__destruct is called only when the object is explicitly destroyed using unset().
Attempts:
2 left
💡 Hint

Think about object lifecycle and script execution.

🚀 Application
expert
2:30remaining
How many times is __destruct called in this PHP script?

Analyze this PHP code. How many times will the __destruct method be called before the script ends?

PHP
<?php
class Logger {
    public function __construct() {
        echo "Logger started\n";
    }
    public function __destruct() {
        echo "Logger ended\n";
    }
}
function createLogger() {
    $log = new Logger();
}
createLogger();
$log = new Logger();
?>
A3
B1
C0
D2
Attempts:
2 left
💡 Hint

Consider when objects go out of scope and when destructors run.

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

  1. Step 1: Understand the role of __construct

    The __construct method is automatically called when a new object is created from a class.
  2. Step 2: Identify its purpose

    It is used to set up or initialize the object, like setting initial values or preparing resources.
  3. Final Answer:

    To initialize an object when it is created -> Option D
  4. 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

  1. Step 1: Recall PHP destructor syntax

    PHP uses the special method named __destruct with two underscores to define destructors.
  2. Step 2: Match the correct syntax

    The correct syntax is function __destruct() {}. Other options are invalid method names for destructors.
  3. Final Answer:

    function __destruct() {} -> Option A
  4. 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

  1. Step 1: Trace constructor execution

    When $obj = new Test(); runs, __construct prints "Start ".
  2. Step 2: Trace echo after object creation

    Next, echo "Middle "; prints "Middle ".
  3. Step 3: Understand destructor timing

    Destructor __destruct runs when script ends or object is destroyed, printing "End" last.
  4. Final Answer:

    Start Middle End -> Option C
  5. 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

  1. Step 1: Check constructor syntax

    The __construct method is missing parentheses () after its name, which is required in PHP.
  2. Step 2: Verify other parts

    The destructor name and syntax are correct, class name capitalization is not mandatory, and echo statements have semicolons.
  3. Final Answer:

    Missing parentheses in __construct method definition -> Option B
  4. 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

  1. 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.
  2. 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.
  3. 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.
  4. Final Answer:

    class FileHandler { private $file; function __construct($filename) { $this->file = fopen($filename, 'r'); } function __destruct() { fclose($this->file); } } -> Option A
  5. 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 unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard