Introduction
Classes and objects are the foundation of Object-Oriented Programming (OOP) in PHP. A class defines the properties and methods that its objects can use. Objects are created from classes and can store different information. In this chapter, you will practise Classes and Objects in PHP creating classes, initializing objects, accessing properties, and working with multiple objects.
Question 1: Create a Simple Class and Object
Problem Statement
Create a class named Car and an object of that class. Display a message using a method named start().
PHP Solution
<?php
class Car
{
public function start()
{
echo "Car Started Successfully!";
}
}
$car = new Car();
$car->start();
?>
Sample Output
Car Started Successfully!
Explanation
class Carcreates a class named Car.start()is a method defined inside the class.$car = new Car();creates an object of the Car class.$car->start();calls the method using the object.- The
newkeyword creates an object. - The
->operator accesses an object’s methods and properties.
A class is a blueprint, while an object is an actual instance created from that blueprint.
Concepts Covered
- Class declaration
- Object creation
- Methods
newkeyword- Object operator (
->)
Question 2: Create a Class with Properties
Problem Statement
Create a class named Student with three properties: name, roll number, and course. Display these properties using an object.
PHP Solution
<?php
class Student
{
public $name = "Rahul";
public $rollNumber = 101;
public $course = "PHP";
}
$student = new Student();
echo "Student Name: " . $student->name . "\n";
echo "Roll Number: " . $student->rollNumber . "\n";
echo "Course: " . $student->course;
?>
Sample Output
Student Name: Rahul
Roll Number: 101
Course: PHP
Explanation
Properties are variables declared inside a class. They store information related to objects.
$namestores the student’s name.$rollNumberstores the student’s roll number.$coursestores the course name.$student->nameaccesses the name property.$student->rollNumberaccesses the roll number.$student->courseaccesses the course.
The public keyword allows these properties to be accessed from outside the class.
Concepts Covered
- Class properties
- Public properties
- Object property access
- Student information
Question 3: Create Multiple Objects from One Class
Problem Statement
Create an Employee class with a property named name. Create three different employee objects and assign a different name to each object.
PHP Solution
<?php
class Employee
{
public $name;
}
$employee1 = new Employee();
$employee1->name = "Amit";
$employee2 = new Employee();
$employee2->name = "Priya";
$employee3 = new Employee();
$employee3->name = "Rahul";
echo $employee1->name . "\n";
echo $employee2->name . "\n";
echo $employee3->name;
?>
Sample Output
Amit
Priya
Rahul
Explanation
A single class can create multiple objects.
Each object maintains its own property values.
$employee1stores Amit’s information.$employee2stores Priya’s information.$employee3stores Rahul’s information.
All three objects use the same class structure, but their data is independent.
Concepts Covered
- Multiple objects
- Object instances
- Independent properties
- Class reusability
Question 4: Assign Values to Object Properties
Problem Statement
Create a Product class with properties for product name and price. Create an object and assign the values after creating it.
PHP Solution
<?php
class Product
{
public $name;
public $price;
}
$product = new Product();
$product->name = "Laptop";
$product->price = 45000;
echo "Product Name: " . $product->name . "\n";
echo "Product Price: " . $product->price;
?>
Sample Output
Product Name: Laptop
Product Price: 45000
Explanation
In this example, the properties are declared without assigning default values.
After creating the object, values are assigned using the object operator.
$product->name = "Laptop";assigns the product name.$product->price = 45000;assigns the product price.- The assigned values can then be accessed through the object.
This approach is useful when object information is available after the object has been created.
Concepts Covered
- Property declaration
- Property assignment
- Object initialization
- Object property access
Question 5: Create a Class with a Constructor
Problem Statement
Create a Book class with a constructor that accepts the book title, author name, and price. Display the details using an object.
PHP Solution
<?php
class Book
{
public $title;
public $author;
public $price;
public function __construct($title, $author, $price)
{
$this->title = $title;
$this->author = $author;
$this->price = $price;
}
public function displayDetails()
{
echo "Book Title: " . $this->title . "\n";
echo "Author: " . $this->author . "\n";
echo "Price: " . $this->price;
}
}
$book = new Book("Learn PHP", "John Smith", 500);
$book->displayDetails();
?>
Sample Output
Book Title: Learn PHP
Author: John Smith
Price: 500
Explanation
A constructor is a special method that runs automatically when an object is created.
__construct()is PHP’s constructor method.$title,$author, and$priceare constructor parameters.$thisrefers to the current object.$this->titlestores the title in the object’s property.$this->authorstores the author’s name.$this->pricestores the book price.
When PHP executes new Book(...), it automatically calls the constructor and assigns the provided values.
Concepts Covered
- Constructor
__construct()- Constructor parameters
$thiskeyword- Object initialization
Question 6: Create Multiple Objects Using a Constructor
Problem Statement
Create a Mobile class with a constructor that accepts the mobile brand and price. Create three mobile objects with different values and display their details.
PHP Solution
<?php
class Mobile
{
public $brand;
public $price;
public function __construct($brand, $price)
{
$this->brand = $brand;
$this->price = $price;
}
public function display()
{
echo "Brand: " . $this->brand . "\n";
echo "Price: " . $this->price . "\n\n";
}
}
$mobile1 = new Mobile("Samsung", 25000);
$mobile2 = new Mobile("Apple", 60000);
$mobile3 = new Mobile("OnePlus", 35000);
$mobile1->display();
$mobile2->display();
$mobile3->display();
?>
Sample Output
Brand: Samsung
Price: 25000
Brand: Apple
Price: 60000
Brand: OnePlus
Price: 35000
Explanation
The same class is used to create three different mobile objects.
$mobile1stores Samsung details.$mobile2stores Apple details.$mobile3stores OnePlus details.- The constructor receives different values for each object.
- The
display()method displays the information stored in the current object.
This demonstrates how one class can represent many real-world items.
Concepts Covered
- Multiple objects
- Constructor
- Object-specific data
- Reusable methods
Question 7: Update Object Properties Using Methods
Problem Statement
Create a BankAccount class with account holder and balance properties. Add a method to update the account balance by depositing money.
PHP Solution
<?php
class BankAccount
{
public $accountHolder;
public $balance;
public function __construct($name, $balance)
{
$this->accountHolder = $name;
$this->balance = $balance;
}
public function deposit($amount)
{
$this->balance = $this->balance + $amount;
}
public function displayBalance()
{
echo "Account Holder: " . $this->accountHolder . "\n";
echo "Current Balance: " . $this->balance;
}
}
$account = new BankAccount("Rahul", 10000);
$account->deposit(5000);
$account->displayBalance();
?>
Sample Output
Account Holder: Rahul
Current Balance: 15000
Explanation
This class stores bank account information and allows the balance to be updated.
- The constructor initializes the account holder and balance.
deposit()accepts the amount to deposit.$this->balanceupdates the balance of the current object.displayBalance()displays the updated account information.
The example assumes that the deposit amount is valid. A real banking application must validate the amount and use appropriate transaction and security controls.
Concepts Covered
- Object properties
- Updating object data
- Class methods
- Constructor
- Object state
Question 8: Create a Class with Multiple Methods
Problem Statement
Create a Rectangle class with length and width properties. Add separate methods to calculate the area and perimeter of the rectangle.
PHP Solution
<?php
class Rectangle
{
public $length;
public $width;
public function __construct($length, $width)
{
$this->length = $length;
$this->width = $width;
}
public function calculateArea()
{
return $this->length * $this->width;
}
public function calculatePerimeter()
{
return 2 * ($this->length + $this->width);
}
}
$rectangle = new Rectangle(10, 5);
echo "Area: " . $rectangle->calculateArea() . "\n";
echo "Perimeter: " . $rectangle->calculatePerimeter();
?>
Sample Output
Area: 50
Perimeter: 30
Explanation
The Rectangle class contains two properties and two methods.
$lengthstores the rectangle’s length.$widthstores its width.calculateArea()returns length multiplied by width.calculatePerimeter()returns twice the sum of length and width.
The object calls both methods to get the required results.
Concepts Covered
- Multiple properties
- Multiple methods
- Constructor
- Returning calculated values
- Object method calling
Question 9: Create an Array of Objects
Problem Statement
Create a Student class with name and marks properties. Create multiple student objects, store them in an array, and display their details using a loop.
PHP Solution
<?php
class Student
{
public $name;
public $marks;
public function __construct($name, $marks)
{
$this->name = $name;
$this->marks = $marks;
}
}
$students = [
new Student("Rahul", 85),
new Student("Priya", 92),
new Student("Amit", 78)
];
foreach ($students as $student) {
echo "Name: " . $student->name . "\n";
echo "Marks: " . $student->marks . "\n\n";
}
?>
Sample Output
Name: Rahul
Marks: 85
Name: Priya
Marks: 92
Name: Amit
Marks: 78
Explanation
An array can store multiple objects.
- Each
new Student(...)creates a separate student object. $studentsstores all three objects.foreachaccesses each object one at a time.$student->namedisplays the current student’s name.$student->marksdisplays the current student’s marks.
This approach is useful when working with collections of employees, products, students, or customers.
Concepts Covered
- Arrays of objects
- Multiple object instances
foreachloop- Object properties
- Managing collections of objects
Question 10: Create an Employee Management Class
Problem Statement
Create an Employee class that stores employee ID, name, department, and monthly salary. Add methods to calculate annual salary and display complete employee details. Create two employee objects.
PHP Solution
<?php
class Employee
{
public $id;
public $name;
public $department;
public $monthlySalary;
public function __construct($id, $name, $department, $salary)
{
$this->id = $id;
$this->name = $name;
$this->department = $department;
$this->monthlySalary = $salary;
}
public function calculateAnnualSalary()
{
return $this->monthlySalary * 12;
}
public function displayDetails()
{
echo "Employee ID: " . $this->id . "\n";
echo "Employee Name: " . $this->name . "\n";
echo "Department: " . $this->department . "\n";
echo "Monthly Salary: " . $this->monthlySalary . "\n";
echo "Annual Salary: " . $this->calculateAnnualSalary() . "\n\n";
}
}
$employee1 = new Employee(101, "Rahul", "IT", 30000);
$employee2 = new Employee(102, "Priya", "HR", 35000);
$employee1->displayDetails();
$employee2->displayDetails();
?>
Sample Output
Employee ID: 101
Employee Name: Rahul
Department: IT
Monthly Salary: 30000
Annual Salary: 360000
Employee ID: 102
Employee Name: Priya
Department: HR
Monthly Salary: 35000
Annual Salary: 420000
Explanation
This example demonstrates how classes and objects can be used to organize employee information.
- The
Employeeclass defines four properties. - The constructor initializes the employee details.
calculateAnnualSalary()calculates the yearly salary.displayDetails()displays all employee information.- Two objects store different employee records.
- Each object calculates its annual salary using its own monthly salary.
The same class structure can be reused to create objects for any number of employees.
Concepts Covered
- Complete class structure
- Multiple properties
- Constructor
- Multiple methods
- Multiple objects
- Reusable calculations
Key Takeaways
- A class is a blueprint used to create objects.
- An object is an instance of a class.
- Properties store information inside a class.
- Methods define the actions that objects can perform.
- The
newkeyword creates an object. - The
->operator accesses object properties and methods. - A constructor initializes object properties automatically.
- The
$thiskeyword refers to the current object. - One class can create multiple independent objects.
- Arrays can store multiple objects for managing collections of data.
Frequently Asked Questions (FAQs)
1. What are classes and objects in PHP?
A class is a blueprint that defines properties and methods. An object is an instance created from that class.
2. How do you create a class in PHP?
Use the class keyword followed by the class name and a pair of braces.
3. How do you create an object in PHP?
Use the new keyword followed by the class name. For example, $student = new Student();.
4. What is the difference between properties and methods?
Properties store data, while methods perform operations. For example, a Student class may have a name property and a display method.
5. What is the purpose of the new keyword?
The new keyword creates an instance of a class, which is called an object.
6. What is the object operator in PHP?
The -> operator is used to access an object’s properties and methods.
7. Can one class have multiple objects?
Yes. You can create many objects from one class, and each object can store different property values.
8. What is a constructor in PHP?
A constructor is a special method named __construct() that runs automatically when an object is created. It is commonly used to initialize properties.
9. What does the $this keyword mean in PHP?
$this refers to the current object. It allows methods to access the properties and other methods of that object.
10. Can we store objects inside an array in PHP?
Yes. PHP arrays can store multiple objects. You can use a foreach loop to access and process each object.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
