Constructors in PHP

Constructors:
When creating a new object,you can pass a list of arguments to the class being called These are passed to a special method within the class,called the constructor,which initializes various properties.
For example:

<?php
class User
{
function User($param1,$param2)
{
//Constructor statement go here
public $username="Guest";
}
}
?>
2.Example for Constructor:

<?php
 
class A
 
{
 
function testA()
 
{
 
echo "This is test method of class A";
 
}
 
function A()
 
{
 
echo "This is user defined constructor of class A"."<br/>";
 
}
 
}
 
$obj= new A();
 
$obj->testA();
 
?>

Output
 This is user defined constructor of class A
 This is test method of class A
2.Example for Constructor:
<?php
    class Person {
        // first name of person
        private $fname;
        // last name of person
        private $lname;
        
        // Constructor
        public function __construct($fname, $lname) {
            echo "Initialising the object...<br/>"; 
            $this->fname = $fname;
            $this->lname = $lname;
        }
        
        // public method to show name
        public function showName() {
            echo "My name is: " . $this->fname . " " . $this->lname; 
        }
    }
    
    // creating class object
    $john = new Person("Abhishek", "Verma");
    $john->showName();
    
?>

OUTPUT:
Initialising the object...
My name is Abhishek Verma



Translate »