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

The Ultimate Guide to Mastering DevOps Through Structured Study Strategies

Introduction The technology landscape has shifted dramatically as organizations migrate to cloud-native architectures and automated delivery pipelines, creating an unprecedented demand for skilled DevOps professionals. Yet, many…

Read More

The Ultimate DevOps Learning Tracker: Measure Skill Growth and Build Real Experience

Introduction Many aspiring engineers step into cloud and automation with immense enthusiasm, collecting hundreds of hours of video tutorials and documentation, only to realize months later that…

Read More

Continuous Testing and CI/CD: The Foundation of Software Quality Improvement

Introduction In today’s fast-paced digital landscape, high software availability and stability are essential, yet traditional development models frequently struggle with siloed teams, manual deployments, and delayed testing…

Read More

GuestPostAI for Smarter Guest Post Creation and Publishing

Search Engine Optimization (SEO) evolves constantly, yet one fundamental truth remains unchanged: high-quality backlinks are the backbone of search visibility. Among all link-building tactics, guest posting continues…

Read More

Top All-in-One Digital Marketing Platform: Why WizBrand is Built for Modern Teams

In the modern hyper-competitive online landscape, running a successful online business requires managing dozens of moving parts. Marketers often find themselves constantly switching between separate software platforms…

Read More

Automated Payment Reconciliation Software: Streamline Your Finances

In today’s fast-paced digital economy, businesses of all sizes live and die by their cash flow. Yet, thousands of enterprises, startups, and service providers continue to grapple…

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