PHP Constructor And Destructor- Tutorialpath

Constructor-Vs-Destructor
Constructor-Vs-Destructor
  • PHP Constructor, If a class name and function name will be similar in that case function is known as constructor.
  • Constructor is special type of method because its name is similar to class name.
  • Constructor automatically calls when object will be initializing.

Types of Constructor:

  1. Default Constructor (user defined constructor)
  2. Pre-define Constructor
  3. Parameterized Constructor

Note: Always prefer pre-defined constructor.

  1.  Example: user defined constructor

 

constructor example
constructor example

Output:

constructor example output
constructor example output

Note : Here we have called testA() method but we didn’t call A() method because it automatically called when object is initialized.

Predefine Constructor

PHP introduce a new functionality to define a constructor i.e __construct().

By using this function we can define a constructor.

It is known as predefined constructor. Its better than user defined constructor because if we change class name then user defined constructor treated as normal method.

Note: if predefined constructor and user defined constructor, both define in the same class, then predefined constructor treat like a Constructor while user defined constructor treated as normal method.

pre defined constructor
pre defined constructor

Output:

pre defined constructor output
pre defined constructor output

Initialize class property using constructor(Value entered by users)

initialize by user oops
initialize by user oops

Output:

initialize by user oops example
initialize by user oops example

Parametrized Constructor:

Parametrized Constructor
Parametrized Constructor

Output:

Parametrized Constructor output
Parametrized Constructor output

Destructor in PHP

The Destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

Destructor automatically call at last.

Note : _ _destruct() is used to define destructor.

destructor function
destructor function

Output:

destructor function output
destructor function output

One thought on “PHP Constructor And Destructor- Tutorialpath

  1. Pingback: NagaPoker

Leave a Reply

Your email address will not be published. Required fields are marked *