PHP OOP Constructor And Destructor

PHP OOP Constructor And Destructor

PHP constructor function is called when the object is created.

The magic method __construct() is known as a constructor that is automatically called whenever a new object is created.

Please keep in mind that the construct function starts with two underscores (__).

The __construct() method should always have public visibility.

When you don't have a constructor (or you have a constructor without arguments), you can create the object from the class without parentheses.


Source Code

Try it now

But, if you have a constructor with arguments, you should send the values for those arguments when you create them.

Source Code

Try it now

PHP Destructor Function

The __destruct() method is executed automatically when the object is destroyed.

Please keep in mind that the destructor function starts with two underscores (__).

Source Code

Try it now
In the above example, the __destruct() method will be called at the end of the execution of the script.