Home ยป PHP Classes and Objects Tutorial

PHP Classes and Objects Tutorial

In PHP, classes and objects are the building blocks of object-oriented programming (OOP). Classes serve as blueprints for creating objects, while objects are instances of classes.

This tutorial covers:

1. Basics of Classes and Objects

A class is a blueprint that defines properties and methods. An object is an instance of that class.

Example: Basic Class and Object

<?php
class Car {
    // Properties
    public $brand;
    public $color;

    // Method
    public function drive() {
        echo "The car is driving.\n";
    }
}

// Create an object
$myCar = new Car();
$myCar->brand = "Toyota";
$myCar->color = "Red";

echo "Brand: " . $myCar->brand . "\n";
echo "Color: " . $myCar->color . "\n";
$myCar->drive();
?>

Output:

Brand: Toyota
Color: Red
The car is driving.

2. Constructors and Destructors

A constructor initializes an object when it is created, and a destructor performs cleanup tasks.

Example: Using Constructor and Destructor

<?php
class Person {
    public $name;

    // Constructor
    public function __construct($name) {
        $this->name = $name;
        echo "Hello, $name!\n";
    }

    // Destructor
    public function __destruct() {
        echo "Goodbye, $this->name!\n";
    }
}

// Create an object
$person = new Person("John");
?>

Output:

Hello, John!
Goodbye, John!

3. Properties and Methods

Properties store object data, and methods define actions.

Example: Defining Properties and Methods

<?php
class Circle {
    public $radius;

    public function __construct($radius) {
        $this->radius = $radius;
    }

    public function calculateArea() {
        return pi() * pow($this->radius, 2);
    }
}

$circle = new Circle(5);
echo "Area: " . $circle->calculateArea() . "\n";
?>

Output:

Area: 78.53981633974483

4. Access Modifiers (public, protected, private)

Access modifiers define the visibility of properties and methods.

Example: Access Modifiers

<?php
class BankAccount {
    private $balance;

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

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

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

$account = new BankAccount(1000);
$account->deposit(500);
echo "Balance: " . $account->getBalance() . "\n";
?>

Output:

Balance: 1500

5. Static Properties and Methods

Static members belong to the class itself and are accessed without creating an object.

Example: Static Members

<?php
class Math {
    public static $pi = 3.14159;

    public static function square($number) {
        return $number * $number;
    }
}

echo "Pi: " . Math::$pi . "\n";
echo "Square of 5: " . Math::square(5) . "\n";
?>

Output:

Pi: 3.14159
Square of 5: 25

6. Inheritance

Inheritance allows a class to derive properties and methods from another class.

Example: Inheritance

<?php
class Animal {
    public function eat() {
        echo "This animal is eating.\n";
    }
}

class Dog extends Animal {
    public function bark() {
        echo "The dog is barking.\n";
    }
}

$dog = new Dog();
$dog->eat();
$dog->bark();
?>

Output:

This animal is eating.
The dog is barking.

7. Polymorphism and Method Overriding

Polymorphism allows overriding methods in derived classes.

Example: Method Overriding

<?php
class Shape {
    public function draw() {
        echo "Drawing a shape.\n";
    }
}

class Circle extends Shape {
    public function draw() {
        echo "Drawing a circle.\n";
    }
}

class Square extends Shape {
    public function draw() {
        echo "Drawing a square.\n";
    }
}

$shapes = [new Circle(), new Square(), new Shape()];
foreach ($shapes as $shape) {
    $shape->draw();
}
?>

Output:

Drawing a circle.
Drawing a square.
Drawing a shape.

8. Practical Examples

Example 1: User Management System

<?php
class User {
    public $username;
    public $email;

    public function __construct($username, $email) {
        $this->username = $username;
        $this->email = $email;
    }

    public function displayInfo() {
        echo "Username: $this->username, Email: $this->email\n";
    }
}

$user = new User("johndoe", "john@example.com");
$user->displayInfo();
?>

Output:

Username: johndoe, Email: john@example.com

Example 2: Shopping Cart

<?php
class Cart {
    private $items = [];

    public function addItem($item) {
        $this->items[] = $item;
    }

    public function displayItems() {
        foreach ($this->items as $item) {
            echo $item . "\n";
        }
    }
}

$cart = new Cart();
$cart->addItem("Apple");
$cart->addItem("Banana");
$cart->displayItems();
?>

Output:

Apple
Banana

Example 3: Student Grades System

<?php
class Student {
    public $name;
    private $grades = [];

    public function __construct($name) {
        $this->name = $name;
    }

    public function addGrade($grade) {
        $this->grades[] = $grade;
    }

    public function calculateAverage() {
        $total = array_sum($this->grades);
        return $total / count($this->grades);
    }
}

$student = new Student("Alice");
$student->addGrade(90);
$student->addGrade(85);
$student->addGrade(88);

echo "Average grade for {$student->name}: " . $student->calculateAverage() . "\n";
?>

Output:

Average grade for Alice: 87.666666666667

Summary

This tutorial introduced the concepts of classes and objects in PHP, covering:

  1. Basics of defining and using classes and objects.
  2. Constructors and destructors for object initialization and cleanup.
  3. Access modifiers for encapsulation.
  4. Static properties and methods for shared data and functionality.
  5. Inheritance and polymorphism for reusable and extendable code.
  6. Practical examples for real-world applications.

You may also like