The following code shows an Example of Creating a Class in PHP. Also, how to create constructor and destructor is also shown.
In this example, we create a class called Students that has five data members – sname, course, marks, percentage, and grade. The function __construct() represents the constructor. Also, the function __destruct() represents the destructor. While, the value of sname, course, and marks are passed as parameters and intialize the first three data members. The value of other two data memebers are computed in the functions get_percentage(), and get_grade() respectively.
As can be seen in the output, when we create objects, the constructors are called first. Also, when the PHP script finishes the execution, the destructors are called for each of the three objects.
<?php
class Student
{
private $sname;
private $course;
private $marks=array();
private $percentage, $grade;
function __construct($sname, $course, $marks)
{
$this->sname=$sname;
$this->course=$course;
$this->marks=$marks;
echo 'Inside constructor....<br>';
}
function __destruct()
{
echo '<br>Destructor called...';
}
function show_details()
{
echo 'Student Name: ',$this->sname,'<br>';
echo 'Course: ',$this->course,'<br>';
echo 'Marks: ','<br>';
$cnt=1;
foreach($this->marks as $v)
{
echo 'Subject ',$cnt++,': ',$v,'<br>';
}
}
function get_percentage()
{
$this->percentage=(array_sum($this->marks)*100)/300;
$str='Percentage: '.round($this->percentage).'%';
return $str;
}
function get_grade()
{
$average=round((array_sum($this->marks)/300)*10);
switch($average)
{
case 9:
case 10: $this->grade='A+';
break;
case 8: $this->grade='A';
break;
case 7: $this->grade='B+';
break;
case 6: $this->grade='B';
break;
case 5:
case 4: $this->grade='C';
break;
default: $this->grade='F';
break;
}
echo '<br>Grade: ',$this->grade;
}
}
$n='Pranav';
$course='MCA';
$m=array(67, 90, 85);
$ob=new Student($n, $course, $m);
$n='Pari';
$course='BCA';
$m=array(56, 39, 42);
$ob1=new Student($n, $course, $m);
$n='Sana';
$course='MCA';
$m=array(17, 32, 41);
$ob2=new Student($n, $course, $m);
$ob->show_details();
echo $ob->get_percentage();
$ob->get_grade();
echo '<br><br>';
$ob1->show_details();
echo $ob1->get_percentage();
$ob1->get_grade();
echo '<br><br>';
$ob2->show_details();
echo $ob2->get_percentage();
$ob2->get_grade();
?>
Output