Object-Oriented Programming (OOP) in PHP with example

By Ved Prakash N | Jul 12, 2023 | PHP
Share : Whatsapp

https://www.fundaofwebit.com/post/object-oriented-programming-oop-in-php-with-example

Object-Oriented Programming (OOP) in PHP with an example


Object-Oriented Programming (OOP) is a paradigm that allows you to structure your code around objects that represent real-world entities. Here's an example in PHP that demonstrates the concept of OOP using a "Person" class:

<?php

class Person {

    // Properties
    public $name;
    public $age;
    public $gender;

    // Constructor
    public function __construct($name, $age, $gender) {
        $this->name = $name;
        $this->age = $age;
        $this->gender = $gender;
    }

    // Method
    public function introduce() {
        return "Hello, my name is {$this->name}, I am {$this->age} years old, and I identify as {$this->gender}.";
    }
}

// Creating objects
$person1 = new Person("Alice", 25, "female");
$person2 = new Person("Bob", 30, "male");

// Accessing object properties
echo $person1->name; // Output: Alice
echo $person2->age; // Output: 30

// Calling object methods
echo $person1->introduce(); // Output: Hello, my name is Alice, I am 25 years old, and I identify as female.
echo $person2->introduce(); // Output: Hello, my name is Bob, I am 30 years old, and I identify as male.

?>


In the example above, we have a `Person` class with properties like name, age, and gender. The constructor __construct() is used to initialize these properties when creating a new instance of the class.

The `introduce()` method is defined within the class, which returns a string introducing the person with their name, age, and gender.

This example demonstrates the basic principles of OOP in PHP, where objects (instances of a class) encapsulate data (properties) and behavior (methods).