search
HomeBackend DevelopmentPHP TutorialPHP OOP Part-Constructor and Destructor

PHP OOP Part-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();

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();

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');

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;

   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();

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

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();

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!

You can connect with me on Linkedin and GitHub.

The above is the detailed content of PHP OOP Part-Constructor and Destructor. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool