OOP

Last updated on

The meaning of OOP is object-oriented programming is a new way of organizing and thinking about your code, making it clearer and easier to manage your projects.

Consider you have a system where your code can mirror objects, behaviors, and interactions. That’s essentially what PHP OOP allows.

You can create “objects” that represent everything in your application, from a single user to an entire inventory of products. Once you get a handle on the basics, you’ll find it can save you time.

What is PHP OOP?

As you may know, PHP Object-Oriented Programming (OOP) is a programming style where you structure code into reusable objects. Each object represents a part of your application, like a user, a product, or a comment.

PHP OOP is not exclusive to PHP—it is a common programming part in many languages like Java, Python, and C++—but here, you will learn how it works with PHP.

In PHP OOP, there are four main concepts: Classes, Objects, Properties, and Methods. Let’s break down each one and see how they all come together.

Classes and Objects

Class is a model or template that defines the properties and behaviors that allow us to use any object from it.

For example, if you have a "User" class, every user object you create from this class will have the same structure but with different specific values, like names and email addresses.

class User {
    public $name;
    public $email;

    public function introduce() {
        return "Hi, I'm " . $this->name;
    }
}

// Creating an object of the User class
$user1 = new User();
$user1->name = "Alice";
$user1->email = "alice@example.com";

echo $user1->introduce(); // Output: Hi, I'm Alice

Just look at the above code, you will find that we have defined a class called User with two properties, $name and $email, and a method, introduce(). Then we created an object which is $user1 from this class. This object has its own values for the name and email, making it unique.

2. Properties and Methods: Defining Characteristics and Actions

Properties in PHP OOP are like variables that belong to a specific class. They define the characteristics of an object. In our User class example, $name and $email are properties. You can consider them as attributes or traits of an object.

While methods are functions within a class that define the actions an object can take. For example, introduce() in the User class is a method that allows a user object to introduce itself. Methods let you interact with an object’s properties.

Let's see more examples in the following section.

PHP OOP Example

Here in this example, you could create classes for products, categories, and orders, organizing each one into a reusable object.

class Product {
    public $name;
    public $price;

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

    public function display() {
        return $this->name . " costs $" . $this->price;
    }
}

$product = new Product("Laptop", 999.99);
echo $product->display(); // Output: Laptop costs $999.99

Let's see the basics of OOP in PHP in the section below.

Principles of PHP OOP

There are four core principles of OOP that guide how classes and objects interact let's see each one with an example.

1- Encapsulation

It protects data by hiding the details and exposing only what’s necessary. It is like putting data in a secure box. Only certain functions (methods) can access or modify this data. By keeping properties private, you prevent unauthorized changes from outside the class.

Here is an example:

class User {
    private $password;

    public function setPassword($password) {
        $this->password = $password;
    }

    public function getPassword() {
        return $this->password;
    }
}

Look at this example, you will find the $password property is private, meaning it cannot be accessed directly outside the class. Instead, we provide public methods setPassword() and getPassword() to control access.

2- Abstraction

This makes complex systems simple by breaking them into objects. You can define a class in broad terms without diving into the details. It allows you to outline necessary actions without the nitty-gritty.

Let's take a look at the below example:

abstract class Animal {
    abstract protected function sound();
}

class Dog extends Animal {
    public function sound() {
        return "Woof!";
    }
}

Here the Animal class is abstract, meaning we can define broad methods (like sound()) without specifying exactly how they work. Then we implement the details in a subclass.

3- Inheritance

It allows classes to adopt properties and methods from other classes. It allows you to create new classes based on existing ones. This helps you avoid rewriting code.

For example:

class Animal {
    public $name;

    public function eat() {
        return $this->name . " is eating.";
    }
}

class Dog extends Animal {
    public function bark() {
        return "Woof!";
    }
}

$dog = new Dog();
$dog->name = "Buddy";
echo $dog->eat(); // Output: Buddy is eating.

Here Dog class inherits from Animal class, which means, it has access to Animal properties and methods, like eat(), but can also have unique methods like bark().

4- Polymorphism

It enables objects to be treated as instances of their parent class. It allows objects to be treated as instances of their parent class especially when working with multiple objects that share the same parent class but behave differently.

Here is an example:

class Cat extends Animal {
    public function sound() {
        return "Meow!";
    }
}

function makeSound(Animal $animal) {
    echo $animal->sound();
}

$dog = new Dog();
$cat = new Cat();

makeSound($dog); // Output: Woof!
makeSound($cat); // Output: Meow!

The makeSound() function can accept any object that is an instance of Animal, showcasing polymorphism in action.

Let's summarize it.

Wrapping Up

PHP OOP is like a big leap if you are new to it, but once you understand the core principles—encapsulation, abstraction, inheritance, and polymorphism—you will see how it transforms your code. It allows you to think in objects, creating structures that are easy to expand, reuse, and troubleshoot.

Thank you for reading. Happy Coding!

Frequently Asked Questions (FAQs)

  • What is PHP OOP?

    PHP Object-Oriented Programming (OOP) is a programming style where code is organized into reusable "objects," representing various parts of an application, like a user, product, or comment. This structure makes code more manageable and helps to avoid duplication.
  • Why should I use PHP OOP?

    Using PHP OOP brings structure and reusability to your code, making it easier to manage and extend. It also allows you to mirror real-world objects and behaviors in your code, which can save you time as your projects grow.
  • What is a class in PHP OOP?

    A class is like a blueprint that defines the properties and behaviors (methods) of an object. For example:
    class User {
        public $name;
        public $email;
    
        public function introduce() {
            return "Hi, I'm " . $this->name;
        }
    }
    
  • How do I create an object in PHP OOP?

    You create an object by using the new keyword with a class. For example:
    $user = new User();
    $user->name = "Alice";
    echo $user->introduce(); // Output: Hi, I'm Alice
    
  • What are properties and methods in PHP OOP?

    Properties are variables that belong to a specific class, like $name and $email in the User class. Methods are functions within a class that define actions an object can perform, like introduce() in the User class.
  • What are the four main principles of PHP OOP?

    The four core principles are:
    1. Encapsulation - Protects data by making some properties or methods private.
    2. Abstraction - Allows defining classes with broad characteristics, focusing only on essential details.
    3. Inheritance - Allows a class to inherit properties and methods from another class.
    4. Polymorphism - Enables objects to be treated as instances of their parent class, even if they behave differently.
  • Can you explain encapsulation with an example?

    Encapsulation restricts access to certain properties, using methods to control access. For example:
    class User {
        private $password;
    
        public function setPassword($password) {
            $this->password = $password;
        }
    
        public function getPassword() {
            return $this->password;
        }
    }
    
    In this example, $password is private and can only be accessed or modified via setPassword() and getPassword() methods.
  • What is inheritance in PHP OOP?

    Inheritance allows a class to adopt properties and methods from another class, reducing repetition. For instance:
    class Animal {
        public $name;
    
        public function eat() {
            return $this->name . " is eating.";
        }
    }
    
    class Dog extends Animal {
        public function bark() {
            return "Woof!";
        }
    }
    
    $dog = new Dog();
    $dog->name = "Buddy";
    echo $dog->eat(); // Output: Buddy is eating.
    
  • What is polymorphism in PHP OOP?

    Polymorphism allows objects of different classes to be treated as instances of a common parent class, making code more flexible. Example:
    class Cat extends Animal {
        public function sound() {
            return "Meow!";
        }
    }
    
    function makeSound(Animal $animal) {
        echo $animal->sound();
    }
    
    $dog = new Dog();
    $cat = new Cat();
    
    makeSound($dog); // Output: Woof!
    makeSound($cat); // Output: Meow!
    
  • How does PHP OOP help with project scalability?

    PHP OOP helps scale projects by structuring code into reusable and organized parts. You can add new features by creating new classes or extending existing ones without major changes to the entire codebase.
  • What is the difference between a class and an object in PHP OOP?

    A class is a blueprint for creating objects, while an object is an instance of a class. For example, User is a class, while $user1 created from User is an object with its own specific properties.
  • How does abstraction work in PHP OOP?

    Abstraction lets you define broad classes with essential methods, leaving details to subclasses. Example:
    abstract class Animal {
        abstract protected function sound();
    }
    
    class Dog extends Animal {
        public function sound() {
            return "Woof!";
        }
    }
    
    The Animal class is abstract, and its sound() method is defined in the Dog subclass, showing how abstraction separates broad concepts from specific implementations.
Share on: