Classes

Introducció

Per definir una classe es comença per la paraula clau class, seguit del nom de la classe i un parell de claus que inclouen les definicions de constants, variables (anomenades "propietats") i funcions (anomenades "mètodes").

<?php

class User
{
    public int $id;
    public ?string $name;

    public function __construct(int $id, ?string $name)
    {
        $this->id = $id;
        $this->name = $name;
    }

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

$user = new User(1234, null);

var_dump($user->id);
var_dump($user->name);

?>

Propietats

Les variables que formen part d'una classes s'anomenen propietats

Les propietas es defineixen declarant la visibilitat (public, protected o private), el tipus (opcional), seguit d'una declaració normal de variable.

Mètodes

La pseudo-variable $this està disponible quan es crida un mètode desde dins del context de l'objecte, i tè com a valor aquest objecte.

Within class methods non-static properties may be accessed by using -> (Object Operator): $this->property (where property is the name of the property). Static properties are accessed by using the :: (Double Colon): self::$property.

Constructor

PHP allows developers to declare constructor methods for classes. Classes which have a constructor method call this method on each newly-created object, so it is suitable for any initialization that the object may need before it is used.