Home >> PHP >> Why use constructor in PHP

Why use constructor in PHP

When we want to give common functionality to the Object during creation of the Object then this functionality must be written into the constructor.

Example:-

class interestCalculator{

     public $rate;
     public $duration;
     public $capital;

     public function __construct($rate, $duration,$capital) {
            $this->capital=$capital;
            $this->rate=$rate;
            $this->duration=$duration;
            $SI=($this->capital*$this->rate*$this->duration)/100;
            echo $SI;
     }
}
$obj=new interestCalculator(3.2,7,2800);

Post Your Comment

Next Questions
Predefined constructor
Parameterized constructor
What is destructor
What is Polymorphism
What is Polymorphism types
What is overloading
What is overriding
What is abstraction
What is abstract class
Implementation of abstract method
What is interface
What is difference between abstract class and interface
What is inheritance
Inheritance types
What is single inheritance
What is multiple inheritance
What is multilevel inheritance
How to use static method and property in inheritance
How to use self and parent with static
How to use self and parent without static
What is visibility
What is the difference between public, private, and protected
What is final
What is final class
What is final method

Copyright ©2022 coderraj.com. All Rights Reserved.