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

Practical Approaches to Continuous Testing in DevOps for Engineering Teams

Introduction Modern software development demands unprecedented speed, but agility without stability leads directly to costly production failures, missed deadlines, and damaged customer trust. Traditional quality assurance acts…

Read More

DevOps Learning Mistakes Beginners Should Avoid: A Practical Career Guide

Introduction The promise of a high-growth, high-impact career makes DevOps one of the most sought-after paths in the tech industry. It sits at the intersection of development,…

Read More

Curated DevOps Reading List Designed for Absolute Technical Beginners

Introduction Entering the world of DevOps can feel overwhelming due to the sheer volume of open-source tools, cloud service platforms, and conflicting tutorials online. While short video…

Read More

Ultimate Goa Travel Guide: Best Places to Visit & Things to Do

Sun-kissed golden sands, swaying palm trees, centuries-old Portuguese architecture, and a vibrant nightlife that lasts until dawn—Goa is a coastal paradise that captures the heart of every…

Read More

Best Cosmetic Hospitals in the World: A Medical Tourism Guide

Choosing to undergo aesthetic surgery is a deeply personal, life-changing decision. Today, high-quality medical care is no longer confined by borders. Millions of patients travel internationally each…

Read More

Discovering the Magic: The Ultimate India Travel Guide

Planning a trip to a country that feels like an entire continent can be overwhelming. From the snow-capped peaks of the Himalayas to the tropical backwaters of…

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