PHP Inheritance

PHP Inheritance

Way1 to inherit one class from another using the keyword extends

<?php

class Course{

                protected $courseCode;

                public function getCode($newCourseCode)

                {

                                $this->courseCode=$newCourseCode;

                }

}

class Subject extends Course{

                protected $subjectName;

                public function getCourse($newSubject)

                {

                                $this->subjectName=$newSubject;

                }

                public function showCourse(){

                                                echo “Student enrolled for <b>”.

                                                $this->subjectName.

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

                                                $this->courseCode;

                }

}

$student = new Subject();

$student->getCode(101);

$student->getCourse(‘Php MySQL’);

$student->showCourse();

?>

Output

Student enrolled for Php MySQL having code 101

Way 2

Inheritance using Scope resolution operator

<?php

class Course{

                protected $courseCode;

                public function getData($newCourseCode)

                {

                                $this->courseCode=$newCourseCode;

                }

}

class Subject extends Course{

                protected $subjectName;

                public function getData($newCourseCode,$newSubject)

                {             

                                parent::getData($newCourseCode);

                                $this->subjectName=$newSubject;

                }

                public function showData(){

                                                echo “Student enrolled for <b>”.

                                                $this->subjectName.

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

                                                $this->courseCode;

                }

}

$student = new Subject();

$student->getData(101,’Php MySQL’);

$student->showData();

?>

Post Your Comments & Reviews

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

*

*