retour
01/03
section 01

Classes, proprietes et methodes

Connectez-vous pour sauvegarder votre progression et acceder aux quiz
Se connecter

La programmation orientee objet (POO) organise le code autour de classes (moules) et d'objets (instances). En PHP moderne, la POO est le paradigme dominant, utilise par tous les frameworks (Symfony, Laravel).

Classe de base

php<?php

class User
{
    // Proprietes (attributs) avec visibilite
    private int $id;
    private string $email;
    private string $nom;
    private int $points = 0;

    // Constructeur : appele lors de new User()
    public function __construct(int $id, string $email, string $nom)
    {
        $this->id = $id;
        $this->email = $email;
        $this->nom = $nom;
    }

    // Methodes publiques (getters)
    public function getId(): int
    {
        return $this->id;
    }

    public function getEmail(): string
    {
        return $this->email;
    }

    public function getNom(): string
    {
        return $this->nom;
    }

    public function getPoints(): int
    {
        return $this->points;
    }

    // Methode publique (setter avec validation)
    public function ajouterPoints(int $points): void
    {
        if ($points < 0) {
            throw new InvalidArgumentException(
                "Les points ne peuvent pas etre negatifs."
            );
        }
        $this->points += $points;
    }

    // Methode avec logique metier
    public function getNiveau(): string
    {
        return match(true) {
            $this->points >= 1000 => "Expert",
            $this->points >= 500  => "Avance",
            $this->points >= 100  => "Intermediaire",
            default               => "Debutant"
        };
    }
}

// Utilisation
$user = new User(1, "[email protected]", "Morvin");
$user->ajouterPoints(150);
echo $user->getNom();      // "Morvin"
echo $user->getPoints();   // 150
echo $user->getNiveau();   // "Intermediaire"

Constructeur promotion (PHP 8.0+)

php<?php
// Avant PHP 8 : verbeux
class UserOld
{
    private string $nom;
    private string $email;

    public function __construct(string $nom, string $email)
    {
        $this->nom = $nom;
        $this->email = $email;
    }
}

// PHP 8+ : constructor promotion (beaucoup plus court)
class User
{
    public function __construct(
        private readonly int $id,
        private string $email,
        private string $nom,
        private int $points = 0,
    ) {}

    // Les proprietes sont declarees ET assignees dans le constructeur
    // readonly = ne peut plus etre modifie apres construction
}

Visibilite

VisibiliteDepuis la classeDepuis l'enfantDepuis l'exterieur
publicOuiOuiOui
protectedOuiOuiNon
privateOuiNonNon

Methodes magiques

php<?php
class Produit
{
    public function __construct(
        private string $nom,
        private float $prix,
    ) {}

    // Appelee par echo $produit
    public function __toString(): string
    {
        return "$this->nom ($this->prix EUR)";
    }

    // Appelee quand on accede a une propriete inexistante
    public function __get(string $name): mixed
    {
        return "Propriete '$name' inexistante";
    }
}

$p = new Produit("Clavier", 79.99);
echo $p;  // "Clavier (79.99 EUR)"
Convention PSR : En PHP, les noms de classes sont en PascalCase (UserRepository), les methodes en camelCase (findById), et les proprietes en camelCase ($firstName). Suivre les PSR (PHP Standards Recommendations) rend votre code compatible avec l'ecosysteme.