PHP Constructor & Destructor

PHP Constructor & Destructor

Create a Course class for student that display their course code and subject enrolled from an institute.

Explanation

Way 1:

<?php

class Course{

            public function __construct()

            {

                        echo “The class “. __CLASS__.” was initiated<br>”;

            }

            public function __destruct()

            {

                        echo “The class “. __CLASS__.” was destroyed”;

            }

}

$student = new Course();

echo “End of File<br>”;

?>

Output

The class Course was initiated
End of File
The class Course was destroyed

Way 2:

<?php

class Course{

            private $courseCode;

            private $subject;

            public function __construct($newCourseCode,$newSubject)

            {

                        $this->courseCode=$newCourseCode;

                        $this->subject=$newSubject;

            }

            public function showData(){

                        echo “Student enrolled for <b>”.

                        $this->subject.

                        “</b> having code <b>”.

                        $this->courseCode;

            }

}

$student = new Course(101,’Php MySQL’);

$student->showData();

?>

Output:

Student enrolled for Php MySQL having code 101

Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

*

*