Q:

PHP program to implement the default or no-argument constructor using __construct()

0

Here, we will create a class that contains the default or no-argument constructor using __construct(), as we know that constructor of a class called automatically when the object of a class gets created.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to implement the default or no-argument constructor using __construct() is given below. The given program is compiled and executed successfully.

<?php  
    //PHP program to implement the default or no argument 
    //constructor using __contruct().
    class Sample
    {  
        public function __construct()
        {  
            echo "Default constructor called<br>";  
        }  
        public function  Method1()
        {  
            echo "Method1 called<br>";  
        }  
    }  
    $S = new Sample();  
    $S->Method1();
?>  

Output:

Default constructor called
Method1 called

Explanation:

In the above program, we created a class Sample that contains a default constructor and a method Method1(), here we implemented constructor using __construct().

$S = new Sample();  

In the above statements, we created the object $S of Sample class then the constructor of Sample class gets called automatically and print "Default constructor called" message on the webpage.

$S->Method1();

In the above statement, we called the Method1() using object $S that will print "Method1 called" message on the webpage.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now