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

DevOps Principles for Effective Software Delivery

Software engineering teams frequently encounter friction when moving code from development to production—from delayed releases and manual deployment errors to communication silos and sudden outages. DevOps Principles…

Read More

Motorcycle Rental in Colombia: Explore Medellín, Bogotá, Cartagena, and More

Introduction Colombia is a land of vivid contrasts. Within a single country, travelers can journey from high Andean mountain passes shrouded in mist down to lush coffee…

Read More

Infrastructure as Code to SRE: Why Operations Engineers Should Embrace DevOps

Introduction For years, the core duties of IT operations teams followed a predictable cadence: provision physical or virtual servers, patch operating systems, monitor system resources, manage storage…

Read More

Motorcycle Rental in Canada: Explore Cities, Scenic Routes, and Road Trip Adventures

Canada offers some of the most dramatic landscapes on earth, from Atlantic coastal coves and dense boreal forests to jagged alpine passes and sweeping prairie skies. Experiencing…

Read More

Why Developers Should Learn DevOps: A Complete Practical Guide

Writing clean, functional code is only the first step in creating reliable software. In modern engineering teams, the journey from a local code editor to a live…

Read More

Complete Guide to Vehicle Rentals: How to Choose Bikes, Scooters, and Cars for Travel and Everyday Mobility

Stepping out of an arrival terminal only to face aggressive taxi touts, surging ride-hailing fees, or confusing bus routes can quickly drain the excitement from any trip….

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