PHP Constructor and Destructor

If the user wants to access any member function of a class then he or she must create the object first then call the member function by this object.

The constructor is a method or way which automatically called when an object the for a class.

No need to call it by an object. Simply constructor is a function which called when object creates of class.

Constructor declares by two ways.

  1. Define function name same as class name. (This is old way to declare constructor. It is use in PHP 5.3.3 version)
  2. Define function by __construct keyword.

Only one constructor creates in one class. It is used to run an operation which needs to run at first of any other operation.

Like Database Connection. The constructor




In above example $dell is an object of Computer class when its created constructor automatically called and CPU, RAM and Hard disk value passed by parameter.

Then when called describe() function its return the whole value


the is also a method or way in OOPS which is opposite of Constructor.

Destructor also called automatically when object an of any class but it’s run when The constructor creates.

It the for free up memory. Using this after complete a task unset all variable and re The constructor it in next program.

Destructor defines by __destruct keyword. an is also a function which automatically called when object The constructor.