PHP Classes and Objects
Create a Course class for student that display their course code and subject enrolled from an institute.
Explanation
Properties:
- course code => 101 => int datatype
- subject => PHP => string datatype
Methods:
- GetData ()
- showData ()
Solution
The $this is in-built or self-referencing variable which refers to the current object
Way 1:
Define variable value and call in the function using object
<? php
class Course {
private $courseCode=101;
private $subject=”Php MySQL”;
public function getData () {
}
public function showData () {
echo “Student enrolled for <b>”.
$this->subject.
“</b> having code <b>”.
$this->courseCode;
}
}
$student = new Course ();
$student->showData ();
?>
Output:
Student enrolled for Php MySQL having code 101
Way 2:
Declare variable and use value at the time of calling in the function using object
<?php
class Course{
private $courseCode;
private $subject;
public function getData($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();
$student->getData(101,”Php MySQL”);
$student->showData();
?>
Output:
Student enrolled for Php MySQL having code 101
Way 3:
- Declare class in one file using any name[‘courseClass]
<?php
class Course{
private $courseCode;
private $subject;
public function getData($newCourseCode,$newSubject){
$this->courseCode=$newCourseCode;
$this->subject=$newSubject;
}
public function showData(){
echo “Student enrolled for <b>”.
$this->subject.
“</b> having code <b>”.
$this->courseCode;
}
}
?>
- Create object in another file by using include function of linking previous class
<?php
include(‘courseClass.php’);
$student = new Course();
$student->getData(101,”Php MySQL”);
$student->showData();
?>
Output:
Student enrolled for Php MySQL having code 101