Change language

PHP Constructors and destructors

Constructors - these are the most basic building blocks that determine the future object and its nature. We can say that Constructors - these are blueprints for creating objects, providing values ​​for member functions and member variables.Once the object is initialized, the constructor is automatically called. Destructors are designed to destroy objects and are automatically called at the end of execution.In this article, we will introduce the object-oriented concepts of constructors and destructors. 
Both are special member functions of any class with different concepts, but the same name, except for destructors, is preceded by a ~ Tildastatement.Syntax:
  • __construct():
    function __construct() {// initialize the object and its properties by assigning // values} 
  • __destruct():
    function __destruct() {// destroying the object or clean up resources here} 
  • Note . The constructor is defined in the public section of the class. Even class property values ​​are set by Constructors.Constructor types:
    • Default constructor:has no parameters, but values ​​can be passed dynamically to the default constructor.
    • Parameterized constructor:accepts parameters, and you can also pass various values ​​to data items.
    • Constructor copy:it takes the address of other objects as a parameter.
    Inheritance.Since Inheritance is an object-oriented concept, Constructors are inherited from parent to child a class derived from it. Whenever a child class has its own constructor and destructor, they are called in order of precedence or preference.Predefined default constructor:with the __construct() function you can define constructor. Note. In the case of a predefined constructor (__ construct) and a custom constructor in the same class, the predefined constructor becomes a constructor, and the custom constructor becomes a regular method.Program : class Tree { function Tree() { echo " Its a User-defined Constructor of the class Tree " ; } function __ construct ( ) { echo " Its a Pre-defined Constructor of the class Tree " ; } } $obj = new Tree(); ?> Output:
    Its a Pre-defined Constructor of the class Tree 
    Parameterized constructor:The class constructor takes arguments or parameters. 
    Operator -> used to set values ​​for variables. In the constructor method, you can assign values ​​to variables during object creation. Program : class Employee { Public $name ; Public $position ; function __ construct ( $name , $position ) { // This is the initialization of the class properties $this -> name = $name ; $this -> profile = $position ; } function show_details() { echo $this -> name. ":" ; echo "Your position is" . $this -> profile. "" ; } } $employee_obj = new Employee ( "Rakesh" , "developer" ); $employee_obj -> show_details(); $employee2 = new Employee ( " Vikas " , "Manager" ); $employee2 -> show_details();  
    Rakesh: Your position is developer Vikas: Your position is Manager 
    Constructors start with two underscores and usually look like regular PHP functions. These constructors are sometimes referred to as magic functions, starting with two underscores and with some additional functionality than normal methods. After creating an object of some class that includes a constructor, the content of the constructor will be executed automatically. Note. If a PHP class has a constructor, then the constructor of the class is called during object creation. Constructors have no return type, so they don’t return anything, not even void.Benefits of using Constructors:
    • Constructors provide the ability to pass parameters that useful for automatically initializing member variables at creation time.
    • Constructors can have as many parameters as required and can be defined using default arguments.
    • They encourage reusability. avoiding reinitialization when instantiating the class.
    • You can start a session in a constructor method so you don’t have to run all functions every time.
    • They can call methods and functions of class members.
    • They can call other constructors even from the parent class.
    Note. The __construct() method always has a public visibility factor. 
    Program : class ParentClass { function __ construct() { print " Parent class constructor. " ; } } class ChildClass extends Parentclass

    { function __ construct() { parent::__ construct(); print "Child Class constructor" ; } } $obj = new ParentClass(); $obj = new ChildClass();  
    Parent class constructor. Parent class constructor. Child Class constructor 
    Note. Every time a child of the class is created, the subclass constructor will be called automatically.Destructor:Destructor is also a special member function that is exactly the opposite of a constructor method and is called when an instance of a class is removed from memory. Destructors (__destruct (void): void) - these are methods that are called when there is no reference to any object of the class, or goes out of scope or is about to be released explicitly.They have no types or return value. It is called only before the memory for the object is removed, or during the completion of PHP scripts, or as soon as the execution control leaves the block. 
    Global objects are destroyed when the complete script or code ends. Resource cleanup before freeing memory or closing files occurs in the destructor method when they are no longer needed in your code. The automatic destruction of class objects is handled by PHP Garbage Collector.
    ~ ClassName() {} 
    Note. The destructor method is called when PHP code is completely executed on the last line using functionsPHP exit()or die() .Program : class SomeClass { function __ construct() { echo "In constructor," ; $this -> name = "Class object!" ; } function __ destruct ( ) { echo " destroying " . $this -> name. "" ; } } $obj = new Someclass();  
    In constructor, destroying Class object! 
    Note. In the case of inheritance, and if both the child and parent class have destructors, the destructor of the derived class is called first, then the destructor of the parent class.Benefits of destructors:
    • Destructors give objects the ability to free memory allocations so that there is enough space for new objects or to free up resources for other tasks.
    • This is effectively makes programs more efficient and very useful as they perform cleaning tasks.
    Comparison between __constructors and __destructors:

    Constructors Destructors Accepts one or more arguments. No arguments are passed. Its void. function name is _construct(). function name is _destruct() It has the same name as the class. It has the same name as the class with prefix ~ tilda. Constructor is involved automatically when the object is created. Destructor is involved automatically when the object is destroyed. Used to initialize the instance of a class. Used to de-initialize objects already existing to free up memory for new accomodation. Used to initialize data memebers of class. Used to make the object perform some task before it is destroyed. Constructors can be overloaded. Destructors cannot be overloaded. It is called each time a class is instantiated or object is created. It is called automatically at the time of object deletion. Allocates memory . It deallocates memory. Multiple constructors can exist in a class. Only one Destructor can exist in a class. If there is a derived class inheriting from base class and the object of the derived class is created,
    the constructor of the base class is created and then the constructor of the derived class. The destructor of the derived class is called and then the destructor of base class just the reverse order of
    constructor. The concept of copy constructor is allowed where an object is initialized from the adress of another object. No such concept is allowed.
    Output: In the real world of programming, the Constructors and Destructor methods are very useful because they make it easier to perform very important tasks during coding. This promotes code reuse without unnecessary repetition. Both are implicitly called by the compiler, even if they are not defined in the class.
    SO 1 data error