PHP Examples For Beginners: OOPS Example Part 1

Welcome to our PHP example blog series for beginners! In this first section, we will delve into the realm of Object-Oriented Programming (OOPS) using real-world PHP examples.

If you’re new to PHP or want to brush up on your OOPS knowledge, this blog series is a great place to start. We cater to newcomers by providing detailed explanations and step-by-step code samples.

Part 1 covers the principles of OOPS in PHP. Classes, objects, properties, and methods will be covered. We’ll walk you through the process of designing your own classes and showing you how to instantiate objects from them. You’ll rapidly comprehend the concepts and principles of OOPS in PHP using real-world settings and simple yet powerful examples.

We’ll explore basic OOPS concepts including encapsulation, inheritance, and polymorphism through hands-on coding tasks. You’ll learn how to build class hierarchies, use inheritance to reuse code, and use polymorphism to improve the flexibility and extensibility of your PHP applications.

By the conclusion of this blog series, you’ll have a good understanding of PHP OOPS and the confidence to use object-oriented programming approaches in your PHP projects. Whether you want to be a PHP developer or just improve your abilities, these examples will provide you with practical information that you can use right now.

Join us on this thrilling voyage through PHP OOPS examples for beginners. Stay tuned for additional installments in this series in which we will go deeper into more sophisticated OOPS ideas and demonstrate their actual application in PHP. Let’s get started and learn OOPS using PHP together!

Table of Contents

Exercise 1: Creating a Class and Object

Create a class called “Person” with properties such as name, age, and email. Implement methods to set and get the values of these properties. Create an object of the class and demonstrate setting and retrieving the values.

class Person {
    private $name;
    private $age;
    private $email;

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

    public function getName() {
        return $this->name;
    }

    public function setAge($age) {
        $this->age = $age;
    }

    public function getAge() {
        return $this->age;
    }

    public function setEmail($email) {
        $this->email = $email;
    }

    public function getEmail() {
        return $this->email;
    }
}

Now, let’s demonstrate how to set and retrieve the values using an object of the Person class:

// Create an instance of the Person class
$person = new Person();

// Set the values using the setter methods
$person->setName('John Doe');
$person->setAge(25);
$person->setEmail('johndoe@example.com');

// Retrieve the values using the getter methods
$name = $person->getName();
$age = $person->getAge();
$email = $person->getEmail();

// Display the retrieved values
echo "Name: " . $name . "<br>";
echo "Age: " . $age . "<br>";
echo "Email: " . $email . "<br>";

When you run this code, it will output:

Name: John Doe
Age: 25
Email: johndoe@example.com

Exercise 2: Inheritance

Create a base class called “Vehicle” with properties such as make, model, and year. Extend this class to create a derived class called “Car” with additional properties such as color and fuel type. Demonstrate the inheritance relationship by accessing both the base class and derived class properties.

class Vehicle {
    protected $make;
    protected $model;
    protected $year;

    public function __construct($make, $model, $year) {
        $this->make = $make;
        $this->model = $model;
        $this->year = $year;
    }

    public function getMake() {
        return $this->make;
    }

    public function getModel() {
        return $this->model;
    }

    public function getYear() {
        return $this->year;
    }
}

class Car extends Vehicle {
    protected $color;
    protected $fuelType;

    public function __construct($make, $model, $year, $color, $fuelType) {
        parent::__construct($make, $model, $year);
        $this->color = $color;
        $this->fuelType = $fuelType;
    }

    public function getColor() {
        return $this->color;
    }

    public function getFuelType() {
        return $this->fuelType;
    }
}

// Create an instance of the Car class
$car = new Car("Honda", "Civic", 2021, "Red", "Petrol");

// Access base class properties using methods from the base class
echo "Make: " . $car->getMake() . "<br>";
echo "Model: " . $car->getModel() . "<br>";
echo "Year: " . $car->getYear() . "<br>";

// Access derived class properties directly
echo "Color: " . $car->getColor() . "<br>";
echo "Fuel Type: " . $car->getFuelType() . "<br>";

When you run this code, it will output:

Make: Honda
Model: Civic
Year: 2021
Color: Red
Fuel Type: Petrol

Exercise 3: Encapsulation

Create a class called “BankAccount” with private properties such as account number and balance. Implement methods to deposit and withdraw funds from the account, ensuring appropriate validation and updating the balance. Demonstrate the encapsulation concept by accessing the methods to perform transactions.

Here’s an example of implementing the encapsulation concept in PHP with a BankAccount the class that encapsulates private properties and methods for managing a bank account:

class BankAccount {
    private $accountNumber;
    private $balance;

    public function __construct($accountNumber, $initialBalance = 0) {
        $this->accountNumber = $accountNumber;
        $this->balance = $initialBalance;
    }

    public function getAccountNumber() {
        return $this->accountNumber;
    }

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

    public function deposit($amount) {
        if ($amount > 0) {
            $this->balance += $amount;
            return true;
        }
        return false;
    }

    public function withdraw($amount) {
        if ($amount > 0 && $amount <= $this->balance) {
            $this->balance -= $amount;
            return true;
        }
        return false;
    }
}

// Create a new BankAccount object
$bankAccount = new BankAccount('1234567890', 1000);

// Access methods to perform transactions
$bankAccount->deposit(500);
$bankAccount->withdraw(200);

// Display account information
echo "Account Number: " . $bankAccount->getAccountNumber() .

When you run this code, it will output:

Account Number: 1234567890
Balance: $1300

In this example, the BankAccount the class encapsulates the private properties accountNumber and balance. The __construct method is used to initialize the account number and balance when creating a new BankAccount object.

The getAccountNumber and getBalance methods provide access to private properties, allowing you to retrieve the account number and balance.

The deposit method allows for depositing funds into the account. It performs validation to ensure that the amount is greater than zero before updating the balance.

The withdraw method allows for withdrawing funds from the account. It validates that the amount is greater than zero and does not exceed the available balance before deducting the amount from the balance.

By accessing the methods deposit and withdraw, you can perform transactions on the BankAccount object, ensuring appropriate validation and updating of the balance.

This demonstrates the concept of encapsulation, where the internal state and behavior of the BankAccount class is encapsulated and accessed through controlled methods.

Exercise 4: Polymorphism

Create a base class called “Shape” with an abstract method called “calculateArea()”. Extend this class to create derived classes such as “Rectangle” and “Circle” that override the “calculateArea()” method. Demonstrate polymorphism by calling the “calculateArea()” method on objects of different shapes.

Certainly! Here’s an example of implementing polymorphism in PHP with a Shape base class and derived classes Rectangle and Circle that demonstrate different implementations of the calculateArea() method:

abstract class Shape {
    abstract public function calculateArea();
}

class Rectangle extends Shape {
    private $width;
    private $height;

    public function __construct($width, $height) {
        $this->width = $width;
        $this->height = $height;
    }

    public function calculateArea() {
        return $this->width * $this->height;
    }
}

class Circle extends Shape {
    private $radius;

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

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

// Create objects of different shapes
$rectangle = new Rectangle(5, 3);
$circle = new Circle(4);

// Call the calculateArea() method on different shapes
echo "Area of Rectangle: " . $rectangle->calculateArea() . "<br>";
echo "Area of Circle: " . $circle->calculateArea();

When you run this code, it will output:

Area of Rectangle: 15
Area of Circle: 50.265482457437

In this example, the Shape class is an abstract class with an abstract method calculateArea(). The Rectangle and Circle classes inherit from Shape and provide their own implementations of the calculateArea() method.

The Rectangle class calculates the area by multiplying its width and height, while the Circle class calculates the area using the formula pi * radius^2.

By creating objects of different shapes and calling the calculateArea() method on them, you demonstrate polymorphism. The method call adapts to the specific implementation of the respective shape, allowing you to calculate the area without knowing the specific shape at runtime.

This showcases the power of polymorphism, where objects of different types can be treated uniformly through a common interface (the Shape base class) while exhibiting different behaviors based on their specific implementations.

Exercise 5: Variable Scope in a Class

Create a class called “Counter” with a private property called “count”. Implement methods to increment the count and retrieve its value. Create an object of the class and demonstrate incrementing the count and retrieving the updated value using the defined methods. Emphasize the concept of variable scope within the class.

here’s an example of a Counter class that demonstrates variable scope within a class, with private property count and methods to increment the count and retrieve its value:

class Counter {
    private $count;

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

    public function increment() {
        $this->count++;
    }

    public function getCount() {
        return $this->count;
    }
}

// Create an object of the Counter class
$counter = new Counter();

// Access the methods to increment the count and retrieve the updated value
$counter->increment();
$counter->increment();
$counter->increment();
$counter->increment();

// Display the updated count value
echo "Count: " . $counter->getCount();

When you run this code, it will output:

Count: 4

In this example, the Counter the class has private property $count that is accessible only within the class. The constructor sets the initial value $count to 0.

The increment method increments the value $count by 1 each time it is called.

The getCount the method retrieves the current value of $count.

By creating an object of the Counter class and calling the increment method multiple times, the count is incremented accordingly. The getCount method is then used to retrieve the updated count value.

The variable $count is scoped within the class, meaning it is not accessible outside the class unless accessed through the defined methods (increment and getCount). This encapsulation ensures that the count value can be managed and retrieved in a controlled manner.

This exercise demonstrates the concept of variable scope within a class, where properties are private by default and can only be accessed through defined methods.

Leave a Comment