Logo

dev-resources.site

for different kinds of informations.

PHP OOP Part-2: Constructor and Destructor

Published at
1/2/2025
Categories
php
oop
beginners
basic
Author
jamir_hossain_8800f85fdd5
Categories
4 categories in total
php
open
oop
open
beginners
open
basic
open
Author
25 person written this
jamir_hossain_8800f85fdd5
open
PHP OOP Part-2: Constructor and Destructor

In this series, I will cover the fundamentals of PHP Object-Oriented Programming (OOP). The content will be organized into sequential parts, each focusing on a specific topic. If you're a beginner or unfamiliar with OOP concepts, this series is designed to guide you step by step. In this part, I will discuss about the constructor and destructor in PHP. Let's begin the journey of learning PHP OOP together!

What is a Constructor?

Let’s first try to understand that what is a Constructor? In simple terms, the constructor is a special method that is automatically called when an object of a class is created. The constructor is used to initialize the properties of the object. It is a magic method in PHP. But now we need to understand about the constructor in detail. Let’s first look at an example of code.

Code Example

class Car
{
   public $name;
   public $color;

   public function setValue(string $name, string $color)
   {
      $this->name  = $name;
      $this->color = $color;
   }

   public function getValue()
   {
      echo "Car name: $this->name\n";
      echo "Car color: $this->color\n";
   }
}

$toyota = new Car;
$toyota->setValue('Toyota', 'Red');
$toyota->getValue();
Enter fullscreen mode Exit fullscreen mode

In the above example, or in the previous section, we set the value of an object using a method. This is called a Setter Method, it means that after creating an object of a class, if we set the value using a method of that object, it is referred to as a Setter Method. However, we can simplify this process using PHP’s built-in magic method. This method is called the constructor, and in PHP, it is defined using __construct(). Let’s look at the following example.

Code Example

class Car
{
   public $name;
   public $color;

   function __construct(string $name, string $color)
   {
      $this->name  = $name;
      $this->color = $color;
   }

   public function getValue()
   {
      echo "Car name: $this->name\n";
      echo "Car color: $this->color\n";
   }
}

$toyota = new Car('Toyota', 'Red');
$toyota->getValue();
Enter fullscreen mode Exit fullscreen mode

In this example, instead of using the setValue method, we’ve used the __construct() method. So, what’s the advantage of using __construct()? In the previous example, after creating an object of the Car class, we had to pass the value for each car using the setValue method. But now, by using __construct(), we can pass the value at the time of object creation, and we don't have to call an additional method.

But now, the question arises: We didn’t call __construct(), so how did it receive the value and set it to the variable?

Code Example

new Car('Toyota', 'Red');
Enter fullscreen mode Exit fullscreen mode

When we use __construct() inside a class, and that constructor receives values from outside, we can pass the values in the first bracket when creating the class object. As soon as we create the object in this way, the __construct() method is automatically called. In other words, whenever we create an instance of a class, the __construct() method it will instantly call. This is how we can initialize the properties of an object using the constructor. Since __construct() is a magic method, so we don’t need to call it explicitly. It will run automatically in specific scenarios to perform certain tasks.

What is a Destructor?

A destructor is also a magic method in PHP. When we create an object using a class, we perform various tasks with that object. But when the tasks are completed, it means the destructor will be triggered when the object is destroyed. The destructor is defined in PHP using __destruct().

Here, it’s important to note that if we create multiple objects using a class, the __destruct() method will be called for each object when all of them are destroyed. In other words, the __destruct() method will be called as many times as the number of objects created using that class. Let’s look at the following example.

Code Example

class Car
{
   public $name;
   public $color;

   function __construct(string $name, string $color)
   {
      $this->name  = $name;
      $this->color = $color;
   }

   public function getValue()
   {
      echo "Car name: $this->name\n";
      echo "Car color: $this->color\n";
   }

   function __destruct()
   {
      echo "I have called\n";
   }
}

$toyota = new Car('Toyota', 'Red');
$toyota->getValue();

$tesla = new Car('Zip', 'Blue');
$tesla->getValue();
Enter fullscreen mode Exit fullscreen mode

If we run this code, we will see the following output.

Car name: Toyota
Car color: Red
Car name: Zip
Car color: Blue
I have called
I have called
Enter fullscreen mode Exit fullscreen mode

Now, you might be wondering in which cases we should use the __destruct() method. When we work with files or databases, we need to open them, but once our tasks are completed, then we need to close the file or database. In such cases, we can use the __destruct() method. Additionally, there are many real-life use cases for the __destruct() method.

I hope now we have some understanding of __construct() and __destruct(). Apart from these methods, there are other important magic methods in PHP, such as __call(), __callStatic(), etc. We can use these methods as well, as they perform certain tasks in various scenarios within a class.

So, that’s all for today. We’ll talk more about another topic in the next lesson. Stay tuned! Happy coding!

basic Article's
30 articles in total
Favicon
Research DevOps metrics and KPIs
Favicon
Matanuska ADR 010 - Architecture, Revisited
Favicon
Matanuska ADR 009 - Type Awareness in The Compiler and Runtime
Favicon
Matanuska ADR 007 - Type Semantics for Primary Types
Favicon
Top 10 Programming Languages in 2025
Favicon
PHP OOP Part-2: Constructor and Destructor
Favicon
PHP OOP Part-4: Static property, method and this vs self
Favicon
PHP OOP Part-3: Access modifier, Encapsulation and Inheritance
Favicon
PHP OOP Part-5: Abstraction and Interface
Favicon
Matanuska ADR 006 - Runtime Exit
Favicon
Load balancer vs Gateway vs reverse proxy vs forward proxy
Favicon
Sponsoring Family in Dubai: Who Can Apply and How?
Favicon
Best practices to Implement RTL in React Js
Favicon
Matanuska ADR 002 - Architecture
Favicon
Matanuska ADR 003 - Recursive Descent Parser
Favicon
Getting Started with Python: Why and How to Learn This Amazing Language
Favicon
Beginner-Friendly Basic Computer Course Overview
Favicon
I'm Publishing Matanuska BASIC's ADRs
Favicon
Engineering of Small Things #2: Cookies
Favicon
PHP OOP Part-7: Composition vs Inheritance and Dependency Injection
Favicon
A Beginner’s Guide to React: Understanding Components
Favicon
Matanuska ADR 008 - Sigils
Favicon
Correct Way to Implement RTL in React Js
Favicon
Hackathon 101
Favicon
Learn javascript promises. Part 1 — What is a promise?
Favicon
PHP OOP Part-6: Polymorphism
Favicon
PHP OOP Part-1: Introduction, Object, and Class
Favicon
Matanuska ADR 005 - Editor Operations
Favicon
Create Class and Object
Favicon
Java basic program with expansion

Featured ones: