Object-Oriented PHP basics

Find out what Object Oriented Programming is and how we can use this programming paradigm in PHP.

If you are just starting with Object-Oriented Programming it might be daunting at first, because it looks more complex. It has a steeper learning curve than procedural but you just have to stick with it and you will grasp this programming paradigm easily. After you master it, it's much easier to read, write and maintain OOP code.

Objective

Get to know the PHP's syntax and building blocks of OOP. What is a Class and what is an Object? Are they the same thing or they represent different things?

Class vs Object

First of all let's shake off this question that you may have, what is a class and what is an object. You may hear someone talking with or about these terms interchangeably, but they are not the same. A class represents a blueprint while an object represents a concrete implementation of that blueprint. Basically is a class until it becomes "usable", that's when we create an instance of that class. In our example we will use a Product.

Creating our Class

Below we have defined our Product class and it holds 4 properties: $name, $price, $currency and $description. At the end we defined a method (called function in procedural) which is a special method (__construct) that is known as magic method and gets executed as soon as we create an object. This __construct method accepts 4 arguments which we than assign to the according properties that we defined above this method.

Properties are basically the equivalent of a variable in OOP, they belong to the class that you defined them in. Every property must start with a visibility declaration which signals how and where you can use this property.

class Product
{
    public $name;

    public $price;

    public $currency;

    public $description;

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

Right now our Product class is doing nothing because we haven't instantiate it yet but we will change that below.

Creating our Object

We can create or instantiate our Product object with the new keyword defined infront of the class name. You can only instantiate a class outside of itself (outside of the class Product { } block). We are creating our Product class with 4 arguments which are needed for the creation of our object.

$monitor = new Product(
    'Dell UltraSharp 27 Monitor',
    479.99,
    '€',
    'See fine details and true-to-life color on this 27” QHD monitor.'
);

Now that we have created our first object we can start using it.

Output simple information about our Product

After we instantiated our Product and saved it to a $monitor variable, we can access its properties by using an "arrow like syntax" -> and than follow that with the property name.

echo $monitor->name . PHP_EOL;
echo $monitor->price . $monitor->currency  . PHP_EOL;
echo $monitor->description . PHP_EOL;

If you open your browser, you should now see the following output:

Dell UltraSharp 27 Monitor
479.99€
See fine details and true-to-life color on this 27” QHD monitor.

Methods

Until now we were just outputting the information that we put in without any modifications to the Product. Let's create a method called getPriceWithVAT() which will calculate the price of our Product with VAT included. Below you will find a new keyword that we haven't used before: $this. This is pointing to the current object in this case to our Product. So from the example below, $this->price will output 479.99 and multiply it by 1.2 so we add our 20% tax. The same goes for other properties that we defined at the start of our class, we can access their values like this: $this->name, $this->currency and $this->description. Add this below the __construct method:

public function getPriceWithVAT(): float
{
    return $this->price * 1.2;
}

Add this below all the echo statements that we have. We can use this method to output price with VAT included like this:

echo 'Price with VAT included: ' . $monitor->getPriceWithVAT() . $monitor->currency;

Now you should see this output from our script:

Dell UltraSharp 27 Monitor
479.99€
See fine details and true-to-life color on this 27” QHD monitor.
Price with VAT included: 575.988€

Multiple instances

You can create as many instances of our Product class as you want and if we wanted to output the details of our Product for more than two or three products the code would get messy quite fast, that's why we will create another method which will handle the "displaying" of our products. Create the following method below the getPriceWithVAT() method:

public function outputProductDetails(): void
{
    printf('%s' . PHP_EOL, $this->name);
    printf('%.3f%s' . PHP_EOL, $this->price, $this->currency);
    printf('%s' . PHP_EOL, $this->description);
    printf('Price with VAT included: %.3f%s' . PHP_EOL, $this->getPriceWithVAT(), $this->currency);
}

Instead of calling echo statements all over the place, now all we have to do to display our Product is instantiate it and call outputProductDetails() method on this instance.

$monitor = new Product(
    'Dell UltraSharp 27 Monitor',
    479.99,
    '€',
    'See fine details and true-to-life color on this 27” QHD monitor.'
);
$monitor->outputProductDetails();

$keyboard = new Product(
    'K840 Mechanical',
    79.99,
    '$',
    'Designed to fit your productive environment at home or in the office.'
);
$keyboard->outputProductDetails();

We have created two objects, one is a monitor and the second is a keyboard. Now you should see these two products with the name, price, description and price with VAT displayed like below:

Dell UltraSharp 27 Monitor
479.990€
See fine details and true-to-life color on this 27” QHD monitor.
Price with VAT included: 575.988€
K840 Mechanical
79.990$
Designed to fit your productive environment at home or in the office.
Price with VAT included: 95.988$

Conclusion

This was an introduction tutorial to the Object-Oriented programming, where we have created a basic Product class, with a few properties and methods which we then used to display Products details.