PHP program to demonstrate the default or no-argument constructor

Here, we are going to demonstrate the default or no-argument constructor in PHP.
Submitted by Nidhi, on November 18, 2020

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

Program/Source Code:

The source code to demonstrate the default or no-argument constructor is given below. The given program is compiled and executed successfully.

<?php  
    //PHP program to demonstrate the 
    //default or no-argument constructor
    class Sample
    {  
        public function  Sample()
        {  
            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().

$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.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.