MOTOSHARE 🚗🏍️
Turning Idle Vehicles into Shared Rides & Earnings

From Idle to Income. From Parked to Purpose.
Earn by Sharing, Ride by Renting.
Where Owners Earn, Riders Move.
Owners Earn. Riders Move. Motoshare Connects.

With Motoshare, every parked vehicle finds a purpose. Owners earn. Renters ride.
🚀 Everyone wins.

Start Your Journey with Motoshare

Complete Tutorial: PHP OOP — Class & Object

Introduction to OOP in PHP

Object-Oriented Programming (OOP) is a programming style that organizes code into objects, which are created from classes. PHP supports OOP concepts that help developers build scalable, reusable, and maintainable applications.

In real-world PHP development—especially in frameworks like Laravel, WordPress plugins, or large DevOps tools—OOP is heavily used to structure code efficiently.


What is a Class in PHP?

class Car {
    public $brand;
    public $color;

    public function startEngine() {
        echo "Engine Started";
    }

A class is a blueprint or template used to create objects.

It defines:

  • Properties (variables)
  • Methods (functions)

Think of a class as:

Blueprint → Object = Real Product

Example:

class Car {
    public $brand;
    public $color;

    public function startEngine() {
        echo "Engine Started";
    }
}

Here:

  • Car → Class
  • $brand, $color → Properties
  • startEngine() → Method

What is an Object in PHP?

An object is an instance of a class.

It represents a real-world entity created from a class blueprint.

Example:

$car1 = new Car();
$car1->brand = "Toyota";
$car1->color = "Red";

$car1->startEngine();

Output:

Engine Started

Here:

  • $car1 → Object
  • new → Creates object
  • -> → Access properties/methods

Basic Class and Object Example

<?php

class Student {

    public $name;
    public $age;

    public function showDetails() {
        echo "Name: " . $this->name;
        echo "<br>";
        echo "Age: " . $this->age;
    }
}

$student1 = new Student();

$student1->name = "Raj";
$student1->age = 25;

$student1->showDetails();

?>

Output:

Name: Raj
Age: 25

Understanding $this Keyword

$this refers to the current object.

Used to access:

  • Properties
  • Methods inside class

Example:

class Employee {

    public $salary;

    public function setSalary($amount) {
        $this->salary = $amount;
    }

    public function getSalary() {
        return $this->salary;
    }
}

Constructor in PHP

A constructor automatically runs when an object is created.

Constructor method:

__construct()

Example:

class Laptop {

    public $brand;
    public $price;

    public function __construct($brand, $price) {
        $this->brand = $brand;
        $this->price = $price;
    }

    public function showLaptop() {
        echo $this->brand . " costs " . $this->price;
    }
}

$l1 = new Laptop("Apple", 2000);
$l1->showLaptop();

Output:

Apple costs 2000

Destructor in PHP

Destructor runs when object is destroyed.

__destruct()

Example:

class Test {

    public function __destruct() {
        echo "Object Destroyed";
    }
}

$t = new Test();

Access Modifiers (Visibility)

Access modifiers control access to properties and methods.

Three types:

  1. Public
  2. Private
  3. Protected

Public

Accessible anywhere.

class User {

    public $username;

    public function show() {
        echo $this->username;
    }
}

Private

Accessible only inside class.

class Bank {

    private $balance = 1000;

    public function getBalance() {
        return $this->balance;
    }
}

Protected

Accessible inside class and child classes.

class ParentClass {

    protected $value = 50;
}

Creating Multiple Objects

You can create many objects from one class.

class Animal {

    public $name;

    public function speak() {
        echo $this->name . " makes sound";
    }
}

$a1 = new Animal();
$a1->name = "Dog";

$a2 = new Animal();
$a2->name = "Cat";

$a1->speak();
echo "<br>";
$a2->speak();

Output:

Dog makes sound
Cat makes sound

Class Methods

Methods are functions inside classes.

Example:

class Calculator {

    public function add($a, $b) {
        return $a + $b;
    }
}

$calc = new Calculator();

echo $calc->add(5, 10);

Output:

15

Static Properties and Methods

Static members belong to class, not objects.

Use:

static

Access using:

ClassName::$property
ClassName::method()

Example:

class Counter {

    public static $count = 0;

    public static function increment() {
        self::$count++;
    }
}

Counter::increment();

echo Counter::$count;

Output:

1

Constants in Class

Defined using:

const

Example:

class Math {

    const PI = 3.14;
}

echo Math::PI;

Output:

3.14

Real-World Example — User Management

class User {

    public $name;
    public $email;

    public function __construct($name, $email) {

        $this->name = $name;
        $this->email = $email;
    }

    public function showUser() {

        echo "Name: " . $this->name;
        echo "<br>";
        echo "Email: " . $this->email;
    }
}

$user1 = new User(
    "Raj",
    "raj@example.com"
);

$user1->showUser();

Real-World Example — Product System

class Product {

    public $name;
    public $price;

    public function __construct($name, $price) {

        $this->name = $name;
        $this->price = $price;
    }

    public function getDiscountPrice($percent) {

        $discount =
            $this->price * $percent / 100;

        return $this->price - $discount;
    }
}

$p1 = new Product(
    "Laptop",
    1000
);

echo $p1->getDiscountPrice(10);

Output:

900

Difference Between Class and Object

FeatureClassObject
DefinitionBlueprintInstance
MemoryNo memoryUses memory
PurposeDefine structureRepresent real entity
ExampleCarToyota Car

Advantages of Using Classes & Objects

  • Code reusability
  • Better organization
  • Easy maintenance
  • Scalability
  • Real-world modeling
  • Security via encapsulation

Best Practices for PHP Classes

Follow these:

  1. Use meaningful class names

Example:

class OrderManager

Not:

class Test

  1. Keep classes focused (Single Responsibility)

Bad:

class User {
    // login
    // payment
    // report
}

Good:

class User
class Payment
class Report

  1. Use constructor initialization

Good:

public function __construct($name)

  1. Use private properties with getters/setters
private $balance;

public function setBalance($amount) {
    $this->balance = $amount;
}

Common Mistakes Beginners Make

Avoid:

Missing $this

Wrong:

name = $name;

Correct:

$this->name = $name;

Forgetting new

Wrong:

$car = Car();

Correct:

$car = new Car();

Accessing private properties directly

Wrong:

$obj->balance;

Correct:

$obj->getBalance();

Practice Exercises

Try these.


Exercise 1 — Create a Book Class

Requirements:

  • Properties: title, author
  • Method: showBook()

Exercise 2 — Create Employee Class

Requirements:

  • Constructor
  • Salary calculation method

Exercise 3 — Static Counter

Requirements:

  • Count number of objects created

Interview Questions (Important)

Q1: What is a class?
A class is a blueprint used to create objects.

Q2: What is an object?
An object is an instance of a class.

Q3: What is $this?
It refers to current object.

Q4: What is constructor?
A method that runs automatically when object is created.

Q5: Difference between class and object?
Class defines structure; object represents real entity.


Summary

In this tutorial you learned:

  • What is a class
  • What is an object
  • How to create objects
  • Constructors and destructors
  • Access modifiers
  • Static members
  • Constants
  • Real-world examples
  • Best practices

Class and Object are the foundation of PHP OOP. Once you understand them well, you can easily learn:

  • Inheritance
  • Polymorphism
  • Encapsulation
  • Abstraction
  • Interfaces
  • Traits

Next Recommended Tutorial

After Class & Object, learn:

  1. Inheritance in PHP
  2. Encapsulation
  3. Polymorphism
  4. Abstraction
  5. Interfaces
  6. Traits

Related Posts

A Practical Guide to Continuous Integration in DevOps

In the past, teams would work in isolation for weeks, sometimes months, hoarding their changes locally. When the time came to merge all that code into the…

Read More

Mastering the DevOps Lifecycle for Scalable Cloud-Native Applications

Introduction In today’s competitive digital landscape, the speed of software delivery has become a critical business differentiator. Organizations are under constant pressure to push features faster, ensure…

Read More

Strategies for Accelerating Release Cycles Using DevOps Deployment Process Engineering

Introduction The software engineering landscapes of recent years have undergone a massive paradigm shift. The rapid growth of cloud-native applications has changed how software is designed, managed,…

Read More

Canada PR CRS Calculator: Check Your Express Entry Score & Immigration Eligibility

Introduction Moving to Canada is a goal shared by professionals, students, and families across the globe. Whether you are driven by the promise of better career opportunities,…

Read More

The Essential Guide to the Austria Red-White-Red Card Scoring System

Introduction Moving to a new country is a life-changing decision. Over the last few years, Austria has quietly emerged as one of the most attractive, stable, and…

Read More

Mastering DevOps Principles for Career Growth and System Reliability

Introduction The landscape of software development has shifted dramatically over the last two decades. We have moved away from the slow, fragmented cycles of the past, where…

Read More
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x