php-clases-y-objetos-en-php

Classes and Objects in PHP

  • 2 min

A class is the definition that groups the state and behavior of a type of object.

In programming:

  • The Blueprint is the CLASS (Class).
  • The House is the OBJECT (Object) or Instance.

Defining a class (class)

A class is the mold. It is a block of code where we define two things:

  1. Properties: Data (variables) that the object will have.
  2. Methods: Behaviors (functions) that it can perform.

Let’s create a class to represent a Drone.

Convention: Class names always start with a Capital letter (PascalCase). Ex: Dron, UserProfile, ShoppingCart.

class Dron {
    // Properties (The state)
    // In modern PHP we TYPE the properties
    public string $modelo;
    public int $bateria = 100; // Default value

    // Methods (The behavior)
    public function despegar(): void {
        echo "The drone is taking off... 🚀\n";
    }
}
Copied!

We just created the blueprint. But we don’t have any drone flying yet.

Creating Objects (new)

To turn that blueprint into something real that occupies memory, we use the keyword new. This process is called Instantiation.

// Create (instantiate) the first object
$miDron = new Dron();

// Create a second completely independent object
$tuDron = new Dron();
Copied!

Now $miDron and $tuDron are real objects. They are of type Dron, but they live separately.

Accessing data (->)

To access the object’s properties or methods, we use the simple arrow ->.

// Assign values
$miDron->modelo = "Mavic Pro";
$tuDron->modelo = "Phantom 4";

// Read values
echo $miDron->modelo; // Output: Mavic Pro
echo $tuDron->modelo; // Output: Phantom 4
Copied!

The pseudo-variable $this

This is where it usually “clicks” for people.

If I am inside the Dron class writing the code for a method (for example, mostrarEstado), how do I reference my own battery? I don’t know what the variable will be called outside ($miDron, $obj1, $x…).

For that, $this exists. $this means: “Myself” or “This current instance”.

Let’s improve our class:

class Dron {
    public string $modelo;
    public int $bateria = 100;

    public function volar(): void {
        // We want to subtract battery from THIS specific drone
        if ($this->bateria > 0) {
            $this->bateria -= 10;
            echo "Voooom! Remaining battery: {$this->bateria}%\n";
        } else {
            echo "Battery depleted. Cannot fly.\n";
        }
    }
}
Copied!

Let’s test independence

$dronA = new Dron();
$dronB = new Dron();

$dronA->volar();
// Output: Voooom! Remaining battery: 90%
// ($dronA used $this to access ITS battery)

echo $dronB->bateria;
// Output: 100
// ($dronB's battery remains intact)
Copied!

When using $this, the property does NOT have the dollar sign.

  • Wrong: $this->$bateria
  • Correct: $this->bateria