Classes with Object

Pre-requisites: Basic Understanding of Programming Language, MySQL.

In this project,

  • We will create a class.
  • The class will be composed of different methods to access data.
  • These methods will be executed with the help of an object.

Type the following code in a PHP editor and save the file as UserClass.php in Classes folder of your root directory.


Classes with Object


Run UserClass.php file in your browser to get the following output. URL may look like as follows:



Code Explanation of UserClass.php


class User{




Class keyword is used to declare a class followed by the classname.


private $con;

Private access specifier is used to declare the class variable.


public function connect($host$user$password$database){




Function connect() is defined to connect to a database using mysqli predefined methods.




$this operator is used to access the private member $con of the class.


public function getEmployeeData(){


This function is defined to retrieve all the employee details from `employees` table.


while($row = mysqli_fetch_assoc($result)){

     $arr['first_name'] = $row['first_name'];

     $arr['last_name'] = $row['last_name'];

     $arr['email_id'] = $row['email_id'];

     $arr['name'] = $row['name'];

     $mainArr[] = $arr;



Records are fetched using while loop and are stored in a main Array.



$userObj = new User;

new keyword is used to create an object of the class. Syntax :

$Objectname = new Classname;



$employeeData = $userObj->getEmployeeData();

Class methods are accessed with the help of created object using arrow operator.


foreach($employeeData as $innerArr){

   echo "<tr>";

   foreach($innerArr as $key => $val){

      echo "<td>".$val."</td>"


   echo "</tr>";


foreach loop has been used to print the data on the screen.




In this project, we have learned to create a Class, declaring variables, defining public member functions of the class, object creation and calling methods outside the class with the help of objects.

Two methods are taken where first method, connect() is defined to connect to a database and second method, getEmployeeData() is defined to retrieve the records from employees table along with their department name.

If records exist, it is printed on screen in the form of table. Otherwise, ‘No Records found’ message is printed.

Help Us to Improve our content

Let's Talk
Go back to Previous Course

© 2021 All rights reserved. – Imagined by Paras Jairath, Developed by P3 Multisolutions & Powered by Network Bulls.