0
0
PHPprogramming~20 mins

__construct and __destruct in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Using __construct and __destruct in PHP Classes
📖 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
Need a 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
Need a 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
Need a 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
Need a hint?

Create the object with new Book("1984", "George Orwell") and print the details with echo.