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.

   class Student
	private $sname;
	private $course;
	private $marks=array();
	private $percentage, $grade;
        function __construct($sname, $course, $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>';
                foreach($this->marks as $v)
			echo 'Subject ',$cnt++,': ',$v,'<br>';
        function get_percentage()
		$str='Percentage: '.round($this->percentage).'%';
		return $str;
	function get_grade()
			case 9:
			case 10: $this->grade='A+';
			case 8: $this->grade='A';
			case 7: $this->grade='B+';
			case 6: $this->grade='B';
 			case 5:
			case 4: $this->grade='C';
			default: $this->grade='F';
		echo '<br>Grade: ',$this->grade;
   $m=array(67, 90, 85);
   $ob=new Student($n, $course, $m);

   $m=array(56, 39, 42);
   $ob1=new Student($n, $course, $m);

   $m=array(17, 32, 41);
   $ob2=new Student($n, $course, $m);

   echo $ob->get_percentage();
   echo '<br><br>';
   echo $ob1->get_percentage();
   echo '<br><br>';
   echo $ob2->get_percentage();


Example of Creating a Class in PHP - Creating Three Objects
Example of Creating a Class in PHP – Creating Three Objects

Further Reading

Examples of Array Functions in PHP

Basic Programs in PHP

Registration Form Using PDO in PHP