Learn PHP Β· 8/14

Object-Oriented Programming (OOP) Part 1: The Basics

7 min read

Course: PHP

Topic: Object-Oriented Programming (OOP) Part 1: The Basics

Hey there, future PHP maestro! πŸ§™β€β™‚οΈ Welcome to the wonderful world of Object-Oriented Programming (OOP). Before we dive in, let's address a quick question: why do we even need this?

Imagine you're building a massive online store. You've got products, users, shopping carts, and orders. With just functions and variables, your code could quickly become a tangled mess, like a bowl of spaghetti 🍝. It would be hard to manage, update, and debug. OOP provides a way to structure our code in a more organized, manageable, and reusable way. It helps us model real-world things (like products or users) into "objects" in our code.

Ready to untangle that spaghetti? Let's get started!


1. Classes and Objects: Blueprints and Instances πŸ“œβž‘οΈπŸš—

The Problem: We need a way to create multiple, consistent "things" in our code. For instance, if we're building a system to manage cars, each car will have a color, a brand, and a model, but the specific values will be different for each car. How can we create a template for what a "car" is?

The Solution: Classes

A class is a blueprint for creating objects. It defines a set of properties (data) and methods (functions) that the objects created from it will have. Think of it as a cookie cutter; the cutter itself isn't a cookie, but it defines the shape of all the cookies you'll make.

Here’s what a simple Car class looks like in PHP:

php
<?php
class Car {
  // Properties and methods will go here
}
?>

Easy, right? We just use the class keyword followed by the name of the class (by convention, it's in PascalCase).

The Solution Part 2: Objects

An object is an instance of a class. It's the actual "thing" created from the blueprint. If our Car class is the cookie cutter, the objects are the delicious cookies πŸͺ themselves. You can create many objects from a single class.

To create an object (or "instantiate a class"), we use the new keyword:

php
<?php
class Car {
  // ...
}

$myCar = new Car();
$anotherCar = new Car();
?>

Now, $myCar and $anotherCar are both objects of the Car class. They are separate and independent instances.

✨ Fun Fact: The concept of object-oriented programming has been around since the 1960s! Simula was the first object-oriented programming language. So, we're building on some solid, time-tested ideas.


2. Properties and Methods: Adding Data and Actions πŸŽ¨βš™οΈ

The Problem: Our Car class is currently an empty shell. It doesn't store any information or do anything. How do we give our car objects attributes like color and brand, and actions like starting the engine?

The Solution: Properties and Methods

Properties are variables within a class that store data. They represent the characteristics of an object. For our Car class, properties could be $color, $brand, and $model.

Methods are functions within a class that define the actions an object can perform. For our Car, a method could be startEngine().

Let's add some properties and a method to our Car class:

php
<?php
class Car {
  // Properties
  public $color = 'red';
  public $brand = 'Toyota';
  public $model = 'Camry';

  // Method
  public function startEngine() {
    return "Engine started!";
  }
}

// Create an object
$myCar = new Car();

// Accessing properties
echo $myCar->color; // Outputs: red

// Calling a method
echo $myCar->startEngine(); // Outputs: Engine started!
?>

To access properties and methods of an object, we use the object operator ->.

You can also change the value of a property:

php
<?php
// ... (Car class definition)

$myCar = new Car();
$myCar->color = 'blue';
echo $myCar->color; // Outputs: blue
?>

3. Visibility Modifiers: Public, Private, Protected πŸšͺπŸ”’

The Problem: Right now, anyone can change the color of our car from anywhere in the code. What if we have a property that shouldn't be changed from outside the class, like a car's unique Vehicle Identification Number (VIN)? We need a way to control access to properties and methods.

The Solution: Visibility Modifiers

PHP provides three visibility modifiers to control access:

  • public: The property or method can be accessed from anywhere (outside the class and by child classes). This is the default if you don't specify any modifier.
  • protected: The property or method can be accessed only within the class itself and by its child classes (we'll cover child classes in a later topic!).
  • private: The property or method can ONLY be accessed from within the class that defined it.

Let's update our Car class with some visibility modifiers:

php
<?php
class Car {
  public $color = 'red';
  protected $brand = 'Toyota';
  private $vin = '12345ABCDE';

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

  private function generateReport() {
    // This can only be called from within the Car class
    return "Generating a top-secret report for VIN: " . $this->vin;
  }
}

$myCar = new Car();

echo $myCar->color; // Works fine, it's public

// The following lines will cause errors!
// echo $myCar->brand;   // Fatal error: Cannot access protected property
// echo $myCar->vin;     // Fatal error: Cannot access private property
// $myCar->generateReport(); // Fatal error: Call to private method
?>

What is $this?
Inside a class's methods, you can use the special variable $this to refer to the current object.

Industry Practice: It's a common practice to make most of your properties private or protected and then create public methods (often called "getters" and "setters") to interact with them. This is a core concept of encapsulation - bundling the data (properties) and the methods that operate on that data into a single unit (the class).


4. Constructor and Destructor Methods: Setup and Teardown πŸ› οΈβ™»οΈ

The Problem: When we create a new Car object, we have to manually set its properties if we want them to be different from the defaults. Isn't there a way to set these properties right when the object is created? Also, what if we need to perform a cleanup action when an object is no longer needed?

The Solution: Constructor and Destructor Methods

Constructor (__construct)

A constructor is a special method that is automatically called when you create an object from a class. It's perfect for setting up initial values for properties. The constructor method is always named __construct().

Let's add a constructor to our Car class:

php
<?php
class Car {
  public $color;
  public $brand;
  public $model;

  public function __construct($color, $brand, $model) {
    $this->color = $color;
    $this->brand = $brand;
    $this->model = $model;
    echo "A new " . $this->color . " " . $this->brand . " " . $this->model . " has been created! πŸš—\n";
  }
}

$car1 = new Car('blue', 'Honda', 'Civic'); // Outputs: A new blue Honda Civic has been created! πŸš—
$car2 = new Car('black', 'Ford', 'Mustang'); // Outputs: A new black Ford Mustang has been created! πŸš—

echo $car1->color; // Outputs: blue
echo $car2->brand; // Outputs: Ford
?>

Destructor (__destruct)

The destructor, named __destruct(), is automatically called when an object is about to be destroyed (for example, when the script finishes running or when the object is explicitly unset). This is useful for cleanup tasks like closing a database connection or a file.

php
<?php
class Car {
  public $color;
  public $brand;

  public function __construct($color, $brand) {
    $this->color = $color;
    $this->brand = $brand;
    echo "A " . $this->brand . " is born!\n";
  }

  public function __destruct() {
    echo "The " . $this->brand . " is being destroyed. 😒\n";
  }
}

$myCar = new Car('red', 'Ferrari');
// The destructor will be called at the end of the script execution.
?>

Under the Hood: PHP's garbage collector automatically handles memory management, so you don't always need to explicitly write a destructor. However, it's good to know it exists for those special cases where you need to perform a specific action before an object is removed.

And that's a wrap for the basics of OOP in PHP! You've learned about classes, objects, properties, methods, visibility, constructors, and destructors. You now have a solid foundation to build more complex and well-structured applications. Keep practicing, and happy coding! πŸ’»


πŸ“š References for Extra Reading

Challenge

You are building a basic inventory management system for an e-commerce platform. Your task is to create a PHP class that models a Product.

Requirements:

  1. Define a class named Product.
  2. The class must have the following properties with the specified visibility:
    • id: private
    • name: protected
    • price: private
    • inventoryCount: protected
  3. Implement a constructor (__construct) that accepts arguments for id, name, and price to initialize the corresponding properties. The inventoryCount should be initialized to 0 within the constructor.
  4. Implement public "getter" methods for all properties: getId(), getName(), getPrice(), and getInventoryCount().
  5. Implement a public method setPrice($newPrice) that updates the product's price. This method should only update the price if the new value is greater than zero.
  6. Create two public methods for inventory management:
    • addToInventory(int $quantity): Adds the specified quantity to the inventoryCount. It should only accept positive integers.
    • sell(int $quantity): Decreases the inventoryCount by the specified quantity. This method should first check if there is sufficient stock. It must return true if the sale is successful and false if there is not enough inventory.
  7. Implement a destructor (__destruct) that will echo the string: "Product [product name] is being removed." where [product name] is the name of the product instance.

Expected result

A PHP script containing a single class named Product that adheres to all the specified requirements.

Class Structure:

  • Class Name: Product
  • Properties:
    • private $id;
    • protected $name;
    • private $price;
    • protected $inventoryCount;
  • Constructor:
    • public function __construct($id, $name, $price)
    • Initializes $this->id, $this->name, and $this->price with the provided arguments.
    • Initializes $this->inventoryCount to 0.
  • Getter Methods:
    • public function getId(): returns the value of $this->id.
    • public function getName(): returns the value of $this->name.
    • public function getPrice(): returns the value of $this->price.
    • public function getInventoryCount(): returns the value of $this->inventoryCount.
  • Setter Method:
    • public function setPrice($newPrice): Contains logic to update $this->price only if $newPrice > 0.
  • Business Logic Methods:
    • public function addToInventory(int $quantity): Contains logic to increase $this->inventoryCount if $quantity > 0.
    • public function sell(int $quantity): Contains logic to check if $this->inventoryCount >= $quantity and $quantity > 0. If true, it decreases the count and returns true. Otherwise, it returns false.
  • Destructor:
    • public function __destruct()
    • Contains an echo statement that outputs a string in the format "Product {$this->name} is being removed.".
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.