What is Class in PHP: Syntax, Example
In PHP or any other programming language, a class is a blueprint or template for creating objects. It is a fundamental building block of Object-Oriented Programming (OOP) in PHP.
A class in PHP defines a structure that groups variables (called properties) and functions (called methods) together into a single, self-contained unit.
For example, imagine you’re an architect designing a house. You don’t build the house directly; instead, you first create a blueprint that defines the structure — such as the number of rooms, the location of doors and windows, and the electrical layout. You can then use that one blueprint to construct multiple real houses (objects).
In PHP:
- The class is the blueprint.
- An object is an actual house built from that blueprint.
Thus, a class encapsulates both properties (attributes) and behaviors (methods) into a single unit. In simple terms, a class defines the data (variables) and the actions (functions) that describe the behavior of an object.
When an object is created from a class, it inherits all the properties and methods defined inside that class. By using classes, you can write reusable, organized, and scalable code.
Real-World Example to Understand Class in PHP
Let’s understand with some more real-world examples what a class means.
1. Car Class
Imagine you are a car manufacturer like Toyota. You design a blueprint (class) for a car that includes the following details:
- Properties (characteristics):
- Color
- Model
- Engine type
- Fuel type
- Methods (behaviors):
- Start the engine
- Stop the car
- Accelerate
This blueprint does not represent a real car itself. It’s just a design. From this blueprint, you can create multiple real cars (objects), such as:
- Car 1: Red Toyota Fortuner (Diesel)
- Car 2: Blue Toyota Glanza (Petrol)
- Car 3: White Toyota Innova (Hybrid)
All of these cars are different objects but built from the same class (Car blueprint).
2. Human Class
Think about a Human class:
- Properties:
- name
- age
- gender
- height
- Methods:
- eat()
- sleep()
- walk()
- talk()
From this blueprint, you can create many objects like:
- John, a 25-year-old man
- Lisa, a 22-year-old woman
Both are instances of the same “Human” class — each having unique property values but sharing common behavior patterns.
From the above examples, it is clear a class is just like a plan or prototype, while objects are the actual things created from that plan.
Why Use Classes? The Benefits of OOP
Before we dive into the syntax, let’s understand why classes are so important in programming:
- Organization: Classes keep all the code related to a single concept neatly organized.
- Code Reusability: Write a class once and create multiple objects from it, eliminating code duplication.
- Maintainability: Updating a class automatically affects all objects created from it, making your code easier to maintain and debug.
- Modularity: Complex applications can be broken down into smaller, manageable classes, which improves structure and readability.
- Inheritance: Reuse existing classes in new ones to avoid rewriting the same code.
- Polymorphism: Perform different actions using the same method name, depending on the object’s type.
- Data Abstraction: Hide unnecessary details from users and expose only the essential features.
Syntax of a PHP Class
The syntax for defining a class in PHP is very simple. The class definition starts with the class keyword followed by the name of the class and a pair of curly braces {}.
// Class definition.
class ClassName {
// Properties (variables)
public $property1;
public $property2;
// Methods (functions)
public function methodName() {
// Code to execute
}
}How to Create a Class in PHP?
Let’s translate the syntax into a practical example. We’ll create a Car class.
Step 1: Declare the Class
To create a class in PHP, we use a class keyword followed by the name of the class and a pair of curly braces {}.
class Car {
// Class body
// We will add properties and methods here.
}Step 2: Define Properties
Properties are represented by variables inside a class. They represent the state or data of an object.
class Car {
// Properties
public $brand;
public $model;
public $color;
}
In this Car class,
- $brand is a property that represents the brand of a car.
- $model is a property that represents the model of a car.
- $color is a property that represents the color of a car.
Step 3: Define Methods
Methods are functions inside a class that performs actions or functionality. They simply define the behavior of the object i.e. what the object can do.
class Car {
// Properties (variables)
public $brand;
public $model;
public $color;
// Method to display car info.
public function getInfo() {
return "This is a $this->color $this->brand $this->model.";
}
}
In this Car class,
- getInfo() is a method that displays the information of the car.
- The keyword public before property and method is an access modifier, which determines the visibility and accessibility of the property and method.
- The public means you can access it from anywhere, both inside and outside from the class.
- Other access modifiers are private and protected which limit the access to the class itself.
Let’s clearly understand about $this->color, $this->brand, and $this->model mean in PHP classes.
Understanding $this in PHP
In PHP, the keyword $this is a special variable that refers to the current object — the instance of the class that is currently being used. When you create an object of a class, PHP uses $this inside the class to refer to that specific object. It is used to access class members such as properties and methods of the object, from within the class itself.
Arrow (->) Operator in PHP
The arrow operator (->) in PHP is an object operator which is used to access properties and methods of an object. It is like a bridge between an object and its data or actions.
Once you have created an object of class, you can use the arrow operator (->) to:
- Access properties (variables) inside the class.
- Call methods inside the class.
Syntax
The general syntax to access variables (properties) and methods is as:
$object->property; // Access or set a property
$object->method(); // Call a methodHere,
- $object → The name of the object you created using a class.
- -> → Arrow operator.
- property or method → The class member you want to use.
Rules for Naming a PHP Class
When you create a class in PHP, you must follow these rules:
- A class name must start with a letter or an underscore (_), followed by any number of letters, numbers, or underscores.
- It cannot start with a number.
- Class names are case-insensitive. However, it is best practice to be inconsistent. For example, Car, car, and CAR would be considered the same, but you should always use Car as defined.
- It is good practice to use PascalCase naming convention. In this naming convention, you start the name with a capital letter, and capitalize the first letter of each subsequent word.
- For example:
- Good: Car, UserProfile, ShoppingCart, BlogPost, CollegeName
- Bad: car, user_profile, shoppingCart, blog_post. These are also valid but don’t follow the standard convention.
Examples of Valid Class Names:
class StudentData {}
class CarModel {}
class _UserAccount {}
Examples of Invalid Class Names:
class 123Car {} // Invalid because this starts with a number.
class car model {} // Invalid because it contains a space.
Basic Example of Class in PHP
Let’s look at a simple PHP class and how it works.
<?php
// Declare properties (variables).
class Car {
public $color;
public $brand;
public $model;
// Declare a method named displayinfo.
public function displayInfo() {
echo "Car Brand: " . $this->brand . "<br>";
echo "Car Model: " . $this->model . "<br>";
echo "Car Color: " . $this->color . "<br>";
}
}
// Create an object of the Car class.
$car1 = new Car();
// Accessing variables and method using arrow operator.
$car1->brand = "Toyota";
$car1->model = "Fortuner";
$car1->color = "White";
$car1->displayInfo();
?>
Output:
Car Brand: Toyota Car Model: Fortuner Car Color: White
In this example,
- $this → Refers to the current object.
- $this->color → Accesses the color property of the current object.
- $this->brand → Accesses the brand property of the current object.
- $this->model → Accesses the model property of the current object.
When $car1->displayInfo() runs:
- $this = $car1
- $this->brand = “Toyota”
- $this->model = “Fortuner”
- $this->color = “White”
Without $this keyword, the class wouldn’t know which object’s data you are talking about.
Conclusion
A class in PHP offers a structured and powerful way to build dynamic, reusable, and secure applications. It is the foundation of object-oriented programming in PHP. It allows you to organize code efficiently and handle complex data relationships.
By understanding the concepts of classes and objects, you can develop scalable web applications with following the best coding practices.



