0
0
PHPprogramming~10 mins

__construct and __destruct in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to define a constructor method in a PHP class.

PHP
<?php
class Car {
    public function [1]() {
        echo "Car created.";
    }
}
?>
Drag options to blanks, or click blank then click option'
A__construct
B__destruct
Cconstructor
Dinit
Attempts:
3 left
💡 Hint
Common Mistakes
Using __destruct instead of __construct
Using a method name without underscores
Using 'constructor' as method name
2fill in blank
medium

Complete the code to define a destructor method in a PHP class.

PHP
<?php
class Car {
    public function [1]() {
        echo "Car destroyed.";
    }
}
?>
Drag options to blanks, or click blank then click option'
A__construct
B__destruct
Cdestroy
Ddelete
Attempts:
3 left
💡 Hint
Common Mistakes
Using __construct instead of __destruct
Using method names like 'destroy' or 'delete'
Forgetting the double underscores
3fill in blank
hard

Fix the error in the constructor method name.

PHP
<?php
class Bike {
    public function [1]() {
        echo "Bike created.";
    }
}
?>
Drag options to blanks, or click blank then click option'
Aconstruct
B__destruct
Cinit
D__construct
Attempts:
3 left
💡 Hint
Common Mistakes
Missing underscores in method name
Using __destruct instead of __construct
Using 'construct' without underscores
4fill in blank
hard

Fill both blanks to create a class with constructor and destructor methods that print messages.

PHP
<?php
class House {
    public function [1]() {
        echo "House built.";
    }
    public function [2]() {
        echo "House demolished.";
    }
}
?>
Drag options to blanks, or click blank then click option'
A__construct
B__destruct
Cdestroy
Dbuild
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping constructor and destructor names
Using 'destroy' or 'build' instead of magic methods
Missing underscores
5fill in blank
hard

Fill all three blanks to create a class that sets a property in the constructor, prints it, and then prints a message in the destructor.

PHP
<?php
class Book {
    public $title;
    public function [1]($name) {
        $this->title = $name;
    }
    public function printTitle() {
        echo $this->[2];
    }
    public function [3]() {
        echo "Book closed.";
    }
}
?>
Drag options to blanks, or click blank then click option'
A__construct
Btitle
C__destruct
DprintTitle
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong method names for constructor or destructor
Accessing property with wrong name
Forgetting $this-> when accessing property