Classes & Objects

Classes & Objects

Classes and objects are something quite important because some programming languages mainly work with them. For example PHP, Java, C++ and Python are mostly object oriented. Object-Oriented Programming (OOP) languages are programming languages that support the object-oriented pattern, which organizes code into objects. Objects are instances of classes, which define properties (attributes) and behaviors (methods).

What is a Class?

A class in PHP is like a blueprint or template used to create objects. It defines the structure of objects, including properties (variables) and methods (functions). You can think of a class as a recipe for making something – it doesn’t do anything on its own until you create an object from it. A hint for when creating classes you will need a fitting name, usually just look for nouns that fit nicely, and speaking out loud can help aswell.

What is an Object?

An object is an instance of a class. When you create an object, you are making a real-world version of the blueprint (class) with actual values assigned to its properties. Each object created from the same class has its own unique data but shares the same structure and behaviour. A hint for when creating objects you will need a fitting name, usually just look for verbs that fit nicely, and speaking out loud can help as well.

Namespace

A namespace is used to make something unique. Its often used with Classes or Interfaces and more. What it does if you have to Classes named Router for example then the namespace is here the define which Router your addressing. Its like when you have two “<p>Hello World!</p>” paragraphs but you only want to adjust one then you give them a class or an id, namespace pretty much does the same.

Here’s an example of a simple class:

PHP
<?php
// Define a class
class Car {
    // Properties (variables that belong to the class)
    public $brand;
    public $color;

    // Constructor (automatically runs when an object is created)
    public function __construct($brand, $color) {
        $this->brand = $brand;  // Assign the value to the object's property
        $this->color = $color;
    }

    // Method (a function inside the class)
    public function describeCar() {
        return "This car is a $this->color $this->brand.";
    }
}

// Creating objects from the class
$car1 = new Car("Toyota", "Red");  // First object
$car2 = new Car("BMW", "Black");   // Second object

// Calling the method
echo $car1->describeCar(); // Output: This car is a Red Toyota.
echo "<br>";
echo $car2->describeCar(); // Output: This car is a Black BMW.
?>

Then here’s an example of a Router class:

PHP
<?php

namespace Core;
use Core\Middleware\Middleware;

class Router
{
    protected $routes = [];

    public function add($method, $uri, $controller)
    {
        $this->routes[] = [
            'uri' => $uri,
            'controller' => $controller,
            'method' => $method,
            'middleware' => null
        ];

        return $this;
    }

    public function get($uri, $controller)
    {
        return $this->add("GET", $uri, $controller);
    }

    public function post($uri, $controller)
    {
        return $this->add("POST", $uri, $controller);
    }

    public function delete($uri, $controller)
    {
        return $this->add("DELETE", $uri, $controller);
    }

    public function patch($uri, $controller)
    {
        return $this->add("PATCH", $uri, $controller);
    }

    public function put($uri, $controller)
    {
        return $this->add("PUT", $uri, $controller);
    }

    public function only($key)
    {
        $this->routes[array_key_last($this->routes)]["middleware"] = $key;

        return $this;
    }

    public function route($uri, $method)
    {
        foreach ($this->routes as $route) {
            if ($route['uri'] === $uri && $route['method'] === strtoupper($method)) {
                Middleware::resolve($route['middleware']);

                return require base_path("Http/controllers/" . $route['controller']);
            }
        }
        $this->abort();
    }

    public function previousUrl()
    {
        return $_SERVER["HTTP_REFERER"];
    }

    protected function abort($code = 404)
    {
        http_response_code($code);

        require base_path("views/{$code}.php");

        die();
    }
}
?>

Another thing to note when adding method’s is that there are 3 different visibility types: public, protected & private. Those will be rather important depending on what you handling or what you want to do.

  • public
    • Accessible from anywhere (inside the class, outside the class, and in child classes).
    • Default visibility if no modifier is specified.
  • protected
    • Accessible inside the class and in child (inherited) classes.
    • Not accessible from outside the class.
    • Useful when you want child classes to access a property but prevent direct access from outside the class.
  • private
    • Accessible only inside the class where it is defined.
    • Not accessible from child classes or outside the class.
    • Used to hide internal data and enforce encapsulation.

Here is a visual look:

Then there’s also inheritance and encapsulation:

  • inheritance
    Inheritance allows a class (child class) to inherit properties and methods from another class (parent class). This helps reuse code without rewriting it.
  • encapsulation
    Encapsulation restricts direct access to certain properties or methods to protect data. We use private and protected access modifiers for this.

An example of inheritance:

PHP
<?php
// Parent class
class Vehicle {
    public $brand;
    
    public function __construct($brand) {
        $this->brand = $brand;
    }

    public function startEngine() {
        return "The engine of $this->brand is starting...";
    }
}

// Child class inheriting from Vehicle
class Car extends Vehicle {
    public $color;

    public function __construct($brand, $color) {
        parent::__construct($brand); // Call the parent class constructor
        $this->color = $color;
    }

    public function describeCar() {
        return "This is a $this->color $this->brand.";
    }
}

// Creating an object from the Car class
$myCar = new Car("Toyota", "Red");

echo $myCar->startEngine(); // Output: The engine of Toyota is starting...
echo "<br>";
echo $myCar->describeCar(); // Output: This is a Red Toyota.
?>

An example of encapsulation:

PHP
<?php
class BankAccount {
    private $balance; // Private property (cannot be accessed directly)

    public function __construct($initialBalance) {
        $this->balance = $initialBalance;
    }

    // Public method to access the private property
    public function getBalance() {
        return "Your balance is $" . $this->balance;
    }

    // Public method to modify the private property
    public function deposit($amount) {
        if ($amount > 0) {
            $this->balance += $amount;
            return "Deposit successful! " . $this->getBalance();
        } else {
            return "Invalid deposit amount.";
        }
    }
}

// Creating an object
$account = new BankAccount(1000);

// Accessing balance via a method (direct access is not allowed)
echo $account->getBalance(); // Output: Your balance is $1000
echo "<br>";
echo $account->deposit(500); // Output: Deposit successful! Your balance is $1500

// Trying to access private property directly (will cause an error)
// echo $account->balance; // This will not work
?>

Getters & Setters (get & set Methods)

Getters and setters in PHP are methods used within a class to control how object properties are accessed and modified. A getter method retrieves the value of a specific property, while a setter method validates and assigns a new value to that property. This approach helps maintain encapsulation by ensuring the internal state of an object is changed only in controlled ways, allowing for consistent validation or additional logic (like logging) whenever a property is read or updated.

Public properties tie you to a specific implementation while getters give you a stable interface that can evolve over time.

Getters allow for:

  • Greater control
  • Opportunity for validation
  • Backward compatibility

Here’s an example:

PHP
<?php  

class User
{
  public function __construct(private string $email)
  {
    //
  }
  
  public function getEmail()
  {
    return $this->email;
  
  }
  
  public function setEmail(string $email)
  {
    if (! filter_var($email, FILTER_VALIDATE_EMAIL)) {
      throw new InvalidArgumentException("Email must be valid.");
    }
    
    $this->email= $email;
  }
}

$user = new User("john@example.com"); // creates / adds the email address: john@example.com as a new user

echo $user->getEmail(); // will output: john@example.com

$user->setEmail("foo@bar.com"); // changes the email address from john@example.com to foo@bar.com

echo $user->getEmail(); // will output: foo@bar.com

$user->setEmail("aaaaaaaaaaaaaaaaaaaaa"); // attempts to change the email address from foo@bar.com to aaaaaaaaaaaaaaaaaaaaa if it fails throw exception

// throws (excpetion) InvalidArgumentException("Email must be valid.")

echo $user->getEmail(); // unreachable, so either remove or wrap in try/catch

Reminder: An exception has to be caught to be considered handled. When setEmail() throws InvalidArgumentException, execution stops and the script never reaches the following echo.
Without a “try / catch“, PHP halts and prints an “Uncaught InvalidArgumentException: Email must be valid.” error message.

Property Hooks (Only PHP 8.4 above!)

Property Hooks refer to the “magic” methods that let you intercept or customize how properties on an object are accessed and modified at runtime. These methods give you fine-grained control over how external code interacts with properties, letting you implement behaviours like lazy loading, dynamic property generation, or validation behind the scenes.

Here’s an example:

PHP
<?php

class User
{
  public string $email {
    get {
      return $this->email;
    }
      
    set {
      if (! filter_var($value, FILTER_VALIDATE_EMAIL)) {
        throw new InvalidArgumentException("Email must be valid.")
      }
      
      $this->email = $value;
    }
  }
  
  public function __construct(string $email)
  {
    $this->email = $email;
  }
}

$user = new User("john@example.com"); // creates / adds the email address: john@example as a new user

echo $user->email; // will output: john@example.com

$user->email = "foo@bar.com"; // changes the email address from john@example.com to foo@bar.com

echo $user->email; // will output: foo@bar.com

$user->email = "aaaaaaaaaaaaaaaaaaaaa";  // changes the email address from foo@bar.com to aaaaaaaaaaaaaaaaaaaaa

echo $user->email; // will output: InvalidArgumentException("Email must be valid.")

Both this code and the one above do the exact same even if they look different.

Interface

An interface is like a simple “to-do list” of methods that a class must have, without telling the class how to do them. When a class “implements” that interface, it must provide all the methods on the list. This helps keep your code organized and makes it easy to swap one class for another, as long as they both follow the same “to-do list.”

Here’s a simple example of a Class that handles the Subscription(s):

PHP
<?php
class Subscription
{
    public function __construct(
        protected BillingPortal $BillingPortal
    ) {

    }

    public function create()
    {
        $this->BillingPortal->getCustomer();
    }

    public function cancel()
    {

    }

    public function swap(string $newPlan)
    {

    }
    public function invoice()
    {

    }
}

interface BillingPortal
{
    public function getCustomer();
    public function getSubscription();
}

class StripeBillingPortal implements BillingPortal
{
    public function getCustomer()
    {

    }

    public function getSubscription()
    {

    }
}

$subscription = new Subscription(
    new StripeBillingPortal()
);

$subscription->create();

This code shows a Subscription class that relies on a BillingPortal (an interface) to handle billing tasks. When you create a new Subscription, you pass in a BillingPortal object (in this case, StripeBillingPortal). The create() method then calls the portal’s getCustomer() function. This structure allows the Subscription class to work with different billing systems just by swapping out the BillingPortal implementation making it easier to adjust.

API

You can find the information here: https://flurin-lernjournal.hosttech.ch/api/

Tags: