PHP Classes and Objects Tutorial
PHP classes and objects tutorial with OOP examples
Object-Oriented Programming (OOP) in PHP starts with classes and objects. These are the building blocks for creating structured, maintainable, and reusable code.
In this tutorial, you will learn:
What a class is
What an object is
How to create classes and objects in PHP
How to define properties and methods
How to use constructors
Real-world developer examples
A class is a blueprint or template used to create objects. It defines:
Properties (variables)
Methods (functions)
Example: A class that represents a Car.
An object is an instance of a class.
It represents a real entity created from the blueprint.
Example: $car1, $car2 are objects of the class Car.
<?php
class Car {
public $brand;
public $color;
public function start() {
echo "Car is starting...";
}
}
$myCar = new Car();
$myCar->brand = "Tata";
$myCar->color = "Red";
echo $myCar->brand; // Output: Tata
$myCar->start(); // Output: Car is starting...
?>
Properties → Variables inside class
Methods → Functions inside class
Example:
class Student {
public $name;
public $age;
public function introduce() {
echo "My name is " . $this->name;
}
}
$st = new Student();
$st->name = "Shubham";
$st->introduce();
$this Keyword
$this refers to the current object.
Used to access class properties and methods from inside the class.
__construct)A constructor runs automatically when an object is created.
class User {
public $name;
public function __construct($name) {
$this->name = $name;
echo "User created: $name";
}
}
$u = new User("Amit");
class Product {
public $name;
public $price;
public function __construct($name, $price) {
$this->name = $name;
$this->price = $price;
}
public function getDetails() {
return $this->name . " - Rs. " . $this->price;
}
}
$p = new Product("Laptop", 55000);
echo $p->getDetails();
$car1 = new Car();
$car1->brand = "Tata";
$car2 = new Car();
$car2->brand = "Mahindra";
Each object has its own properties.
class Animal {
public $type = "Dog";
}
$a = new Animal();
echo $a->type; // Dog
class MathOperations {
public function add($a, $b) {
return $a + $b;
}
}
$m = new MathOperations();
echo $m->add(10, 20);
class UserProfile {
public $name;
public $email;
public function __construct($name, $email) {
$this->name = $name;
$this->email = $email;
}
public function showProfile() {
echo "Name: {$this->name}<br>Email: {$this->email}";
}
}
$user = new UserProfile("Shubham", "shubham@example.com");
$user->showProfile();
You learned:
What classes and objects are
How to define properties and methods
How to use constructors
How to create real-world OOP examples
Classes and objects are the foundation of OOP in PHP.