Master Objects in PHP: Your Friendly Guide to OOP

Spread the love

Objects In PHP: Today, we’re going to explore the wonderful world of objects and Object-Oriented Programming (OOP) in PHP. Buckle up, because we’re about to break down some key concepts in a way that’s easy to understand and implement in your projects.

This is the second article in my PHP OOPS Series. The following is a list of articles from this series.

  1. Understanding Class in PHP: Building Blocks of Object-Oriented Programming
  2. Master Objects in PHP: Your Friendly Guide to OOP

Objects In PHP: Building Blocks of OOP

Imagine a blueprint for a house. This blueprint defines the structure, rooms, and overall layout. In OOP, a class acts like this blueprint. It defines the properties (like name, members) and behaviors (like adding members) of an object.

Objects In PHP, on the other hand, is a single instance of that class. Think of it as an actual house built from the blueprint. You can have multiple houses (objects) based on the same blueprint (class).

Let us consider a class “Team” which is responsible to mange a team.

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

    public function members()
    {
        //
    }

    public function add($name)
    {
        //
    }

    public function cancel()
    {
        //
    }

    public function manager()
    {
        //
    }
}

Now the above “Team” class with some basic behavior associated with any team we create in our system. We have the blueprint ready and we can create any number of team instances which is called “Objects“.

If you are preparing for Interviews you can look into the following set of questions:

Creating Objects with “new”

Let us create our first “Object” using the keyword “new“. We will be passing some values to the constructor and then access the value with a provided method “name()” . We can call such method as “accessor/getter“.

class Team()
{
    protected $name;

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

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

    public function members()
    {
        //
    }

    public function add($name)
    {
        //
    }

    public function cancel()
    {
        //
    }

    public function manager()
    {
        //
    }
}

$acme = new Team('Acme');

echo $acme->name(); // Acme

Now the above team object have only a name. Let us add some members to the team.

class Team()
{
    protected $name;

    protected $members = [];


    public function __constructor($name, $members = [])
    {
        $this->name = $name;
        $this->members = $members;
    }

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

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

    public function add($name)
    {
        $this->members[] = $name;
    }

    public function cancel()
    {
        //
    }

    public function manager()
    {
        //
    }
}

$acme = new Team('Acme');
$acme->add("John Doe");
$acme->add("Jane Doe");

print_r($acme->members());

Or If you see in the above constructor method we have added one more parameter which accepts the initial members. We can use this to add initial members and then later we can use the “add()” method to add new members.

... Team class here


$acme = new Team('Acme', [
    "John Doe",
    "Jane Doe"
]);

// Later we can do
$acme->add("New Team Member");

print_r($acme->members());

Key points to remember:

  • A class defines the blueprint for objects.
  • An object is an instance of a class.
  • You can have multiple objects from the same class.

Create object using “Static constructor”

In the above examples we are using the keyword “new” to create an objects in php. But we can use something called “Static Constructor” which is more elegant way of creating an objects in php.

class Team()
{
    protected $name;

    protected $members = [];

    public function __constructor($name, $members = [])
    {
        $this->name = $name;
        $this->members = $members;
    }

    // This is the Static Constructor
    public static function start(...$params)
    {
        return new static($params);
    }

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

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

    public function add($name)
    {
        $this->members[] = $name;
    }

    public function cancel()
    {
        //
    }

    public function manager()
    {
        //
    }
}

$acme = Team::start('Acme', [
    "John Doe",
    "Jane Doe"
]);

Now remember, we can name the static constructor anything we want which represents the real world. Here we used “start()” because “Team::start()” is more aligned to the real world. If you want you can name the Static Constructor as “build()” which we can use as “Team::build()“;

Now, a public static method which is also referred as “Class Method” is affectively global. We can use this anywhere in the system.

NOTE: Be cautious when using static method which changes anything in the system. In the above case it is only creating a Instance of a class which is safe to use.

Clean up

Until now we are using “Strings” to add members which represents their names. Now what if we want more information about the members like email, address, dob etc.

We can pass member objects in php instead of the string.

... Teams class

class Member
{
    protected $name;
    protected $dob;

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

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

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

    public function lastViewed()
    {
        //
    }
}


$acme = Team::start('Acme', [
    new Member("John Doe", date("Y/m/d")),
    new Member("Jane Doe", date("Y/m/d")),
]);

Conclusion

In this article, we’ve discovered the essence of classes, objects, and their interactions. Remember that a class is more than just a collection of code; it is a blueprint that represents real-world entities. Objects in php, on the other hand, are the material forms of these blueprints, each with their own unique characteristics.

In our next article, we’ll look at Inheritance. Until then, happy coding, and may your objects always provide clarity and efficiency in your PHP projects!