Hello! Welcome to the fifth lesson in our module on Object-Oriented PHP Fundamentals.
In our last lesson, we saw how the $this keyword allows an object to refer to its own properties and methods. We manually created an object and then set its properties line by line. While this works, it can be cumbersome and error-prone. What if you forget to set a crucial property? The object might be left in an invalid or incomplete state.
Today, we'll solve that problem by learning about two special "magic methods" that manage an object's lifecycle: constructors and destructors. You will learn how to use a constructor (__construct) to initialize an object's state the moment it's created, ensuring it's always valid and ready to use. We will also cover the destructor (__destruct), which handles cleanup tasks when an object is no longer needed.
1. The Constructor: Initializing Objects
A constructor is a special method within a class that is automatically called when you create a new instance of that class using the new keyword. Its primary purpose is to initialize the object's properties, making the object immediately usable.
The constructor method is always named __construct. The double underscore prefix signals to PHP that this is a "magic method" with special behavior.
Let's see how this works. Instead of this:
// The old way
$user = new User();
$user->username = 'Alice';
$user->email = 'alice@example.com';
We can use a constructor to do it all in one step:
// The constructor way
$user = new User('Alice', 'alice@example.com');
This is cleaner, more reliable, and a fundamental practice in modern OOP.
To understand the syntax and see it in action, let's watch a video that walks through creating a constructor.
PHP Classes & Objects - Typed Properties - Constructors & Destructors - Full PHP 8 Tutorial
The video 'PHP Classes & Objects' by Program With Gio provides a clear, practical demonstration of defining a constructor, passing arguments to it, and using $this to initialize properties.
Watch the segment from 07:38 to 09:40. Pay close attention to how the __construct method is defined and how arguments passed to new Transaction(...) are used to set the object's properties.
Constructor Code Examples
Now that you've seen the concept, let's explore some code examples to solidify your understanding. The following reading provides several clear examples, from a basic implementation to more advanced techniques.
PHP Constructor and Destructor Tutorial: Complete Guide
The article 'PHP Constructor and Destructor Tutorial' from Oatllo offers excellent, bite-sized code examples. We'll look at a few of them.
Read the sections 'Simplest constructor' and 'Constructor with defaults and validation'. Notice how the second example makes the $price parameter optional and adds a check to prevent negative prices.
As you can see, constructors can also have default values for parameters (e.g., float $price = 0.0) and can contain logic to validate the initial data. This makes your objects much more robust.
PHP 8 Constructor Property Promotion
PHP 8 introduced a fantastic feature called constructor property promotion. It's a shorthand syntax that lets you declare class properties directly in the constructor's signature, reducing boilerplate code.
Consider this standard constructor:
class Product
{
public string $name;
public float $price;
public function __construct(string $name, float $price)
{
$this->name = $name;
$this->price = $price;
}
}
With property promotion, you can write the same class like this:
class Product
{
public function __construct(
public string $name,
public float $price
) {}
}
By adding a visibility modifier (public, protected, or private) to a constructor parameter, PHP automatically creates a property with the same name and assigns the argument's value to it. The constructor body can be empty or contain additional logic. This is the preferred, modern way to write constructors in PHP 8 and newer.
Let's review the official example.
PHP Constructor and Destructor Tutorial: Complete Guide
The same Oatllo article has a great section on this modern feature.
Read the section 'Property promotion (PHP 8+)' to see how it simplifies the Order class.
2. The Destructor: Cleaning Up
Just as a constructor runs at the beginning of an object's life, a destructor runs at the very end. The destructor method, named __destruct, is automatically called when an object is about to be destroyed. This happens when there are no more references to the object, or when the script finishes execution.
Destructors are less common than constructors but are useful for performing cleanup tasks, such as:
- Closing a database connection.
- Closing a file handle.
- Releasing a lock on a resource.
The video we watched earlier also has an excellent section on destructors.
PHP Classes & Objects - Typed Properties - Constructors & Destructors - Full PHP 8 Tutorial
Let's return to the Program With Gio video to learn about the __destruct method. The presenter does a great job of explaining exactly when the destructor is called.
Watch from 14:36 to 17:31. Note the difference in when the destructor runs depending on whether a reference to the object still exists. Also, listen for the practical use cases he mentions.
A common use case for a destructor is to ensure a temporary file is deleted when the object managing it is destroyed.
PHP Constructor and Destructor Tutorial: Complete Guide
This practical example from the Oatllo article shows how a destructor can be used to automatically clean up a temporary file.
Read the code example under the 'Destructor for cleanup' heading. See how the __destruct method checks if the file exists and then deletes it.
Important Note: While useful, you shouldn't rely on destructors for critical, time-sensitive operations. Their exact execution time can be unpredictable. For crucial cleanup, especially with error handling, a try...finally block is often a more reliable choice (a topic we will cover later).
Hands-on Practice
Now, let's put this knowledge into practice. Imagine you are building a simple blog application. Create a BlogPost class.
- Define Properties: The class should have the following
privateproperties:$title,$content, and$author. - Create a Constructor:
- Implement a
__constructmethod that accepts the title, content, and author as arguments. - Use constructor property promotion (the PHP 8+ way) to declare the properties and initialize them.
- Implement a
- Create a Display Method: Add a
publicmethod calleddisplay()thatechos the blog post in a simple format (e.g., "Title by Author: Content"). - Create a Destructor: Implement a
__destructmethod that simplyechos a message like"Post '{$this->title}' is being destroyed.\n"to help you visualize when the object is cleaned up. - Instantiate and Use:
- Create a
BlogPostobject with some sample data. - Call its
display()method.
- Create a
Click to see a possible solution
<?php
class BlogPost
{
public function __construct(
private string $title,
private string $content,
private string $author
) {
echo "New post created: '{$this->title}'\n";
}
public function display(): void
{
echo "--- Blog Post ---\n";
echo "{$this->title} by {$this->author}\n";
echo "{$this->content}\n";
echo "-----------------\n\n";
}
public function __destruct()
{
echo "Post '{$this->title}' is being destroyed.\n";
}
}
// Instantiate the object
$post1 = new BlogPost(
'PHP Constructors',
'Constructors are magic methods that initialize objects.',
'Alex'
);
// Use the object
$post1->display();
// The script ends here, so the destructor for $post1 will be called.
?>
Conclusion
Excellent work! You've now learned how to control the entire lifecycle of an object in PHP. Constructors and destructors are essential tools for writing robust, predictable, and professional object-oriented code.
Key Takeaways:
- The constructor (
__construct) is a magic method called automatically when an object is created withnew. It's used to initialize properties and ensure the object starts in a valid state. - The destructor (
__destruct) is a magic method called automatically when an object is destroyed. It's used for cleanup tasks like releasing resources. - Constructor property promotion (PHP 8+) is a modern, concise syntax for declaring and initializing properties at the same time.
- Using constructors is fundamental for creating reliable objects and is a standard practice in modern PHP development.
Preview of the Next Lesson:
We've now covered properties, methods, visibility, $this, and the object lifecycle. In our next lesson, we will explore another important member of a class: class constants. These are values that belong to the class itself (not any specific object instance) and are guaranteed to never change.