Back-end · formation gratuite

PHP Training

Develop dynamic server-side web applications

  • Intermédiaire
  • 14 chapitres
  • Exemples de code
  • 100 % gratuit
Commencer le cours

Introduction to PHP

PHP (Hypertext Preprocessor) is an open-source server-side scripting language designed specifically for web development. Created in 1994 by Rasmus Lerdorf, PHP is now one of the most used languages for creating dynamic and interactive websites.

🌐 What is PHP?

PHP is a programming language that runs on the server side, unlike JavaScript which runs in the browser. This means PHP code is processed on the web server before the page is sent to the user's browser.

💡 How does PHP work?

  1. User requests a web page (e.g., my-site.com/page.php)
  2. Web server (Apache/Nginx) receives the request
  3. Server executes the PHP code contained in the file
  4. PHP generates dynamic HTML
  5. Server sends HTML to user's browser
  6. Browser displays the web page

🚀 Why learn PHP?

PHP is an excellent choice to start web development for several reasons:

  • ✅ Popular - Used by 77% of websites worldwide, including giants like WordPress, Facebook, Wikipedia, and Yahoo
  • ✅ Easy to learn - Simple and intuitive syntax, similar to C and Java
  • ✅ Powerful - Allows creating complete web applications: e-commerce sites, social networks, content management systems
  • ✅ Free and Open-Source - No license cost, cross-platform (Windows, Linux, macOS)
  • ✅ Large community - Millions of developers, complete documentation, many learning resources
  • ✅ Easy integration - Works perfectly with MySQL, HTML, CSS, JavaScript
  • ✅ Modern frameworks - Laravel, Symfony, CodeIgniter for rapid development

📋 Prerequisites for learning PHP

Before starting with PHP, it is recommended to have basic knowledge of:

  • ✅ HTML - To structure web page content
  • ✅ CSS - To style web pages
  • ⚠️ JavaScript - Useful but not required at the start

💡 Important note: PHP requires a web server to function. You can install a local development environment like XAMPP, WAMP (Windows), MAMP (Mac), or LAMP (Linux) which include Apache, MySQL, and PHP.

🎯 PHP Use Cases

PHP is used to create many types of web applications:

  • Dynamic websites - Pages that change based on data
  • 🛒 E-commerce - Online stores, shopping carts
  • Content management systems - WordPress, Drupal, Joomla
  • Social networks - Forums, blogs, community platforms
  • Email sending - Contact forms, newsletters

📝 PHP Syntax

PHP syntax is simple and intuitive. All PHP code must be placed between opening <?php and closing ?> tags. The code is then executed on the server and the result is sent to the browser as HTML.

🔤 PHP Tags

PHP uses special tags to delimit code:

  • <?php ?> - Standard tags (recommended)
  • <? ?> - Short tags (require configuration)
  • <?= ?> - Equivalent to echo (since PHP 5.4)

Basic example:

<?php
  // Ceci est un commentaire sur une ligne
  /* Ceci est un commentaire
    sur plusieurs lignes */

  echo "Hello World!"; // Affiche "Hello World!"
?>

📤 Content Display

PHP offers several ways to display content:

  • echo - Displays one or more strings (most used)
  • print - Displays a single string (returns 1 on success)
  • var_dump() - Displays detailed information about a variable (debugging)
  • print_r() - Displays a variable in a readable way (debugging)

Display examples:

<?php
// echo - le plus utilisé
echo "Bonjour"; // Affiche: Bonjour
echo "Bonjour ", "Monde"; // Affiche: Bonjour Monde

// print - similaire à echo
print "Hello"; // Affiche: Hello

// var_dump - pour déboguer
$age = 25;
var_dump($age); // Affiche: int(25)
?>

📝 Important Syntax Rules

  • ✅ Statements end with a semicolon (;)
  • ✅ PHP is case-sensitive for variable names ($Name ≠ $name)
  • ✅ Function names are not case-sensitive (ECHO = echo)
  • ✅ Spaces and line breaks are generally ignored
  • ✅ Comments are not executed

💡 Important note: PHP files must have the .php extension and be executed on a web server (Apache, Nginx). You cannot simply open a PHP file in your browser like an HTML file. You must go through a local or remote web server.

📦 Variables

Variables in PHP are containers that store data. They are essential for creating dynamic applications. Unlike other languages, PHP automatically determines the variable type based on the assigned value.

📝 Naming Rules

  • ✅ Must start with the $ symbol followed by a letter or underscore
  • ✅ Can contain letters, numbers, and underscores
  • ✅ Are case-sensitive ($nom ≠ $Nom ≠ $NOM)
  • ❌ Cannot start with a number
  • ❌ Cannot contain spaces or special characters (except underscore)

Examples of valid and invalid variables:

<?php
// ✅ Variables valides
$nom = "Jean";
$age = 25;
$_prix = 19.99;
$nomUtilisateur = "admin"; // camelCase recommandé
$est_actif = true; // snake_case aussi valide

// ❌ Variables invalides (généreraient des erreurs)
// $2nom = "Jean"; // Erreur: ne peut pas commencer par un chiffre
// $nom utilisateur = "admin"; // Erreur: espace interdit
// $nom-utilisateur = "admin"; // Erreur: tiret interdit
?>

💾 Value Assignment

Assignment is done with the = operator. PHP automatically determines the variable type.

Practical examples:

<?php
// Variables de différents types
$nom = "Jean"; // String (chaîne de caractères)
$age = 25; // Integer (entier)
$prix = 19.99; // Float (décimal)
$estActif = true; // Boolean (booléen)
$ville = NULL; // NULL (vide)

// Utilisation des variables
echo "Bonjour " . $nom; // Affiche: Bonjour Jean
echo "Vous avez " . $age . " ans"; // Affiche: Vous avez 25 ans

// Réassignation (changement de valeur)
$age = 26; // La variable $age vaut maintenant 26
?>

🔄 Variable variables

PHP allows you to use the content of a variable as the name of another variable. These are called "variable variables".

Variable variable example:

<?php
$nom = "age"; // $nom contient la chaîne "age"
$$nom = 25; // Crée $age = 25
echo $age; // Affiche: 25
?>

💡 Best practice: Use descriptive and consistent variable names. Prefer $nomUtilisateur over $n or $x. This makes your code more readable and maintainable.

🔢 Data Types

PHP is a dynamically and weakly typed language. This means you don't need to declare a variable's type before using it, and PHP can automatically change a variable's type based on context. PHP supports 8 primitive data types.

📝 String (Character String)

A string is a sequence of characters, like text. Strings can be delimited by single quotes (') or double quotes (").

String examples:

<?php
// Guillemets simples (littéral)
$nom = 'Jean'; // String
echo 'Bonjour $nom'; // Affiche: Bonjour $nom (pas d'interpolation)

// Guillemets doubles (avec interpolation)
$prenom = "Marie";
echo "Bonjour $prenom"; // Affiche: Bonjour Marie
echo "Bonjour {$prenom}"; // Même résultat (syntaxe recommandée)

// Concaténation
$message = "Bonjour " . $prenom . " !"; // Utilise le point (.)
?>

🔢 Integer

An integer is a number without a decimal part. It can be positive, negative, or zero.

Integer examples:

<?php
$age = 25; // Integer positif
$temperature = -10; // Integer négatif
$zero = 0; // Zéro
$grand = 2147483647; // Maximum sur 32 bits

// Opérations arithmétiques
$somme = 10 + 5; // 15
$produit = 4 * 7; // 28
?>

🔢 Float (Decimal Number)

A float (or double) is a number with a decimal part. Used for calculations requiring decimal precision.

Decimal examples:

<?php
$prix = 19.99; // Float
$pi = 3.14159; // Float
$pourcentage = 0.15; // 15%
$scientifique = 1.5e3; // 1500 (notation scientifique)

// Calcul avec décimaux
$total = 19.99 + 5.50; // 25.49
?>

✅ Boolean

A boolean represents a truth value. It can only have two values: true or false.

Boolean examples:

<?php
$estActif = true; // Boolean true
$estConnecte = false; // Boolean false

// Utilisation dans les conditions
if ($estActif) {
  echo "Le compte est actif";
}

// Conversion en booléen
$valeur = 1; // true en contexte booléen
$valeur = 0; // false en contexte booléen
$valeur = ""; // false (chaîne vide)
?>

📚 Array

An array stores multiple values in a single variable. PHP supports indexed and associative arrays.

Array examples:

<?php
// Tableau indexé (ancienne syntaxe)
$fruits = array("Pomme", "Banane", "Orange");

// Tableau indexé (syntaxe courte PHP 5.4+)
$legumes = ["Carotte", "Tomate", "Salade"];

// Tableau associatif
$personne = [
  "nom" => "Jean",
  "age" => 30,
  "ville" => "Paris"
];

// Accès aux éléments
echo $fruits[0]; // "Pomme"
echo $personne["nom"]; // "Jean"
?>

🎯 Object

An object is an instance of a class. We will see objects in detail in the OOP section.

❌ NULL

NULL represents a variable with no value. A variable is NULL if it has been assigned to NULL or has never been assigned.

Examples with NULL:

<?php
$ville = NULL; // NULL explicite
$nom; // NULL (non initialisée)

// Vérifier si une variable est NULL
if (is_null($ville)) {
  echo "La variable est NULL";
}
?>

🔍 Type checking

PHP provides several functions to check a variable's type:

Type checking functions:

<?php
$texte = "Hello";
$nombre = 42;
$decimal = 3.14;
$tableau = [1, 2, 3];

// Vérifications
is_string($texte); // true
is_int($nombre); // true
is_float($decimal); // true
is_array($tableau); // true
is_bool(true); // true
is_null(NULL); // true

// Obtenir le type
gettype($texte); // "string"
var_dump($nombre); // int(42)
?>

💡 Type conversion: PHP can automatically convert types based on context. For example, <code>"5" + 3</code> will give <code>8</code> (integer) because PHP converts the string to a number. You can also force a conversion with <code>(int)</code>, <code>(string)</code>, <code>(float)</code>, <code>(bool)</code>, <code>(array)</code>.

➕ Operators

Operators are symbols that allow you to perform operations on values. PHP has several categories of operators: arithmetic, comparison, logical, assignment, and more.

🔢 Arithmetic Operators

Arithmetic operators perform basic mathematical operations.

Arithmetic operators:

<?php
$a = 10;
$b = 3;

// Addition
$somme = $a + $b; // 13

// Soustraction
$difference = $a - $b; // 7

// Multiplication
$produit = $a * $b; // 30

// Division
$quotient = $a / $b; // 3.333...

// Modulo (reste de la division)
$reste = $a % $b; // 1 (10 ÷ 3 = 3 reste 1)

// Exponentiation (PHP 5.6+)
$puissance = $a ** $b; // 1000 (10³)
?>

🔀 Comparison operators

Comparison operators compare two values and return true or false.

Comparison operators:

<?php
$a = 5;
$b = "5"; // Chaîne "5"
$c = 10;

// Égalité (valeur seulement)
$egal = ($a == $b); // true (5 == "5")

// Identité (valeur ET type)
$identique = ($a === $b); // false (int !== string)

// Différent
$different = ($a != $c); // true
$different = ($a <> $c); // true (même chose)

// Non identique
$nonIdentique = ($a !== $b); // true

// Supérieur / Inférieur
$superieur = ($c > $a); // true (10 > 5)
$inferieur = ($a < $c); // true (5 < 10)
$superieurEgal = ($a >= 5); // true
$inferieurEgal = ($a <= 5); // true
?>

⚠️ Important: The difference between == and === is crucial. == compares only values (with type conversion), while === compares values AND types. Use === to avoid subtle bugs!

🔗 Logical Operators

Logical operators combine boolean conditions.

Logical operators:

<?php
$age = 25;
$estActif = true;
$aPermis = false;

// ET logique (&& ou and)
if ($age >= 18 && $estActif) {
  echo "Majeur et actif";
}

// OU logique (|| ou or)
if ($estActif || $aPermis) {
  echo "Actif ou a permis";
}

// NON logique (!)
if (!$aPermis) {
  echo "Pas de permis";
}
?>

📝 Assignment operators

Assignment operators assign values to variables. PHP offers combined assignment operators to simplify code.

Assignment operators:

<?php
$x = 10; // Affectation simple

// Affectation combinée
$x += 5; // Équivaut à: $x = $x + 5 (résultat: 15)
$x -= 3; // Équivaut à: $x = $x - 3 (résultat: 12)
$x *= 2; // Équivaut à: $x = $x * 2 (résultat: 24)
$x /= 4; // Équivaut à: $x = $x / 4 (résultat: 6)
$x %= 5; // Équivaut à: $x = $x % 5 (résultat: 1)

// Concaténation avec affectation
$texte = "Hello";
$texte .= " World"; // Équivaut à: $texte = $texte . " World"
echo $texte; // "Hello World"
?>

🔗 Concatenation Operator

The . (dot) operator allows you to concatenate (join) character strings.

Concatenation examples:

<?php
$prenom = "Jean";
$nom = "Dupont";
$age = 30;

// Concaténation simple
$nomComplet = $prenom . " " . $nom; // "Jean Dupont"

// Concaténation avec variables
$message = "Bonjour " . $prenom . ", vous avez " . $age . " ans";
// "Bonjour Jean, vous avez 30 ans"

// Avec guillemets doubles (interpolation)
$message2 = "Bonjour $prenom, vous avez $age ans"; // Plus simple !
?>

➕ Increment and decrement operators

These operators increase or decrease a variable by 1.

Increment and decrement:

<?php
$x = 5;

// Pré-incrémentation (incrémente puis retourne)
echo ++$x; // Affiche: 6 (x vaut maintenant 6)

// Post-incrémentation (retourne puis incrémente)
$x = 5;
echo $x++; // Affiche: 5 (mais x vaut maintenant 6)
echo $x; // Affiche: 6

// Décrémentation
$x = 5;
echo --$x; // Affiche: 4
echo $x--; // Affiche: 4 (mais x vaut maintenant 3)
?>

🔀 Conditions

Conditional structures allow you to execute code only if certain conditions are met. This is one of the fundamental concepts of programming, allowing you to create applications that react differently based on situations.

app.formations.php.conditions_if_title

app.formations.php.conditions_if_text

Basic example with if:

<?php
$age = 18;

// Structure if simple
if ($age >= 18) {
  echo "Vous êtes majeur";
}

// Structure if / else
if ($age < 18) {
  echo "Vous êtes mineur";
} else {
  echo "Vous êtes majeur";
}

// Structure if / elseif / else (conditions multiples)
if ($age < 18) {
  echo "Mineur";
} elseif ($age == 18) {
  echo "Tout juste majeur";
} elseif ($age < 65) {
  echo "Majeur";
} else {
  echo "Senior";
}
?>

❓ Ternary Operator

The ternary operator is a concise way to write a simple if/else condition on a single line.

Ternary operator syntax:

<?php
$age = 20;

// Syntaxe: (condition) ? valeur_si_vrai : valeur_si_faux
$statut = ($age >= 18) ? "Majeur" : "Mineur";
echo $statut; // "Majeur"

// Équivalent à:
if ($age >= 18) {
  $statut = "Majeur";
} else {
  $statut = "Mineur";
}

// Ternaire imbriqué (à utiliser avec modération)
$note = 85;
$resultat = ($note >= 90) ? "Excellent" : ($note >= 70) ? "Bien" : "À améliorer";
?>

🔄 switch Structure

The switch structure is useful when you have multiple conditions to check on the same variable. It is often more readable than a series of if/elseif.

Example with switch:

<?php
$jour = "lundi";

switch ($jour) {
  case "lundi":
    echo "Premier jour de la semaine";
    break; // Important: arrête l'exécution
  case "vendredi":
    echo "Dernier jour de travail";
    break;
  case "samedi":
  case "dimanche":
    echo "Week-end !";
    break;
  default:
    echo "Jour de semaine";
}

// Exemple avec nombres
$note = 85;
switch (true) {
  case ($note >= 90):
    echo "Excellent";
    break;
  case ($note >= 70):
    echo "Bien";
    break;
  default:
    echo "À améliorer";
}
?>

⚠️ Important: Never forget the <code>break</code> in a <code>switch</code>! Without <code>break</code>, PHP will continue to execute the following cases (this is called "fall-through"). This is sometimes intentional (as in the Saturday/Sunday example), but usually it's an error.

✅ Conditions with logical operators

You can combine multiple conditions with logical operators && (AND), || (OR), and ! (NOT).

Examples with logical operators:

<?php
$age = 25;
$estActif = true;
$aPermis = true;

// ET logique (les deux conditions doivent être vraies)
if ($age >= 18 && $estActif) {
  echo "Majeur et actif";
}

// OU logique (au moins une condition doit être vraie)
if ($age >= 18 || $aPermis) {
  echo "Majeur ou a permis";
}

// NON logique (inverse la condition)
if (!$estActif) {
  echo "Compte inactif";
}

// Conditions complexes
if (($age >= 18 && $estActif) || $aPermis) {
  echo "Accès autorisé";
}
?>

🎯 Practical Use Cases

Here are some concrete examples of using conditions in real-world situations:

Exemple 1 : Vérification d'authentification

<?php
$estConnecte = true;
$estAdmin = false;

if ($estConnecte) {
  if ($estAdmin) {
    echo "Bienvenue administrateur";
  } else {
    echo "Bienvenue utilisateur";
  }
} else {
  echo "Veuillez vous connecter";
}
?>

Exemple 2 : Calcul de remise

<?php
$montant = 150; // Montant d'achat
$remise = 0; // Remise en pourcentage

if ($montant >= 200) {
  $remise = 20; // 20% de remise
} elseif ($montant >= 100) {
  $remise = 10; // 10% de remise
} elseif ($montant >= 50) {
  $remise = 5; // 5% de remise
}

$montantFinal = $montant - ($montant * $remise / 100);
echo "Montant: $montant€, Remise: $remise%, Total: $montantFinal€";
?>

🔁 Loops

Loops allow you to repeat instructions multiple times without having to rewrite the same code. This is a fundamental concept that allows you to automate repetitive tasks and process data collections.

🔄 for Loop

The for loop is used when you know in advance how many times you want to repeat the code. It consists of three parts: initialization, condition, and increment.

for loop syntax:

<?php
// Syntaxe: for (initialisation; condition; incrémentation)
// Exemple simple: compter de 0 à 4
for ($i = 0; $i < 5; $i++) {
  echo $i . " "; // Affiche: 0 1 2 3 4
}

// Compter de 1 à 10
for ($i = 1; $i <= 10; $i++) {
  echo $i . " ";
}

// Compter à rebours de 10 à 1
for ($i = 10; $i >= 1; $i--) {
  echo $i . " "; // Affiche: 10 9 8 7 6 5 4 3 2 1
}

// Compter par pas de 2
for ($i = 0; $i <= 10; $i += 2) {
  echo $i . " "; // Affiche: 0 2 4 6 8 10
}
?>

🔄 while Loop

The while loop repeats the code as long as a condition is true. It is useful when you don't know in advance how many iterations will be needed.

Exemples avec while :

<?php
// Exemple simple
$i = 0;
while ($i < 5) {
  echo $i . " ";
  $i++; // Important: incrémenter pour éviter la boucle infinie
}

// Exemple pratique: générer des nombres jusqu'à atteindre 100
$nombre = 1;
while ($nombre <= 100) {
  echo $nombre . " ";
  $nombre *= 2; // Multiplier par 2 à chaque itération
} // Affiche: 1 2 4 8 16 32 64
?>

app.formations.php.loops_dowhile_title

app.formations.php.loops_dowhile_text

Example with do...while:

<?php
$i = 0;
do {
  echo $i . " ";
  $i++;
} while ($i < 5);

// Même si la condition est fausse au début, le code s'exécute une fois
$x = 10;
do {
  echo "Exécuté au moins une fois";
} while ($x < 5); // Condition fausse, mais s'exécute quand même
?>

🔄 foreach Loop

The foreach loop is specifically designed to iterate through arrays and objects. It is the most used loop in PHP for processing data collections.

foreach with indexed arrays:

<?php
$fruits = ["Pomme", "Banane", "Orange"];

// Syntaxe simple (valeur seulement)
foreach ($fruits as $fruit) {
  echo $fruit . "<br>";
}
// Affiche: Pomme, Banane, Orange

// Syntaxe avec clé et valeur
foreach ($fruits as $index => $fruit) {
  echo "Index $index: $fruit<br>";
}
// Affiche: Index 0: Pomme, Index 1: Banane, Index 2: Orange
?>

foreach with associative arrays:

<?php
$personne = [
  "nom" => "Jean",
  "age" => 30,
  "ville" => "Paris"
];

foreach ($personne as $cle => $valeur) {
  echo "$cle: $valeur<br>";
}
// Affiche: nom: Jean, age: 30, ville: Paris
?>

⏹️ Loop control: break and continue

The break and continue keywords allow you to control loop execution.

break et continue :

<?php
// break - arrête complètement la boucle
for ($i = 0; $i < 10; $i++) {
  if ($i == 5) {
    break; // Arrête la boucle quand i = 5
  }
  echo $i . " "; // Affiche: 0 1 2 3 4
}

// continue - passe à l'itération suivante
for ($i = 0; $i < 10; $i++) {
  if ($i % 2 == 0) { // Si i est pair
    continue; // Passe au suivant sans exécuter le reste
  }
  echo $i . " "; // Affiche seulement les impairs: 1 3 5 7 9
}
?>

🎯 Practical Use Cases

Here are concrete examples of using loops in real-world situations:

Example 1: Display a list of users

<?php
$utilisateurs = ["Jean", "Marie", "Pierre", "Sophie"];

echo "<ul>";
foreach ($utilisateurs as $utilisateur) {
  echo "<li>$utilisateur</li>";
}
echo "</ul>";
// Génère une liste HTML avec tous les utilisateurs
?>

Example 2: Calculate the sum of an array

<?php
$nombres = [10, 20, 30, 40, 50];
$somme = 0;

foreach ($nombres as $nombre) {
  $somme += $nombre; // Ajoute chaque nombre à la somme
}

echo "La somme est: $somme"; // Affiche: La somme est: 150
?>

💡 Best practice: Use foreach to iterate through arrays rather than for when possible. It's more readable, safer (no risk of index error), and more performant.

⚡ Functions

Functions are reusable code blocks that perform a specific task. They allow you to organize your code, avoid repetition, and facilitate maintenance. PHP has thousands of built-in functions, but you can also create your own functions.

📝 Create a Function

To create a function, use the function keyword followed by the function name and parentheses containing parameters (optional).

Basic syntax:

<?php
// Fonction simple sans paramètres
function direBonjour() {
  echo "Bonjour !";
}

direBonjour(); // Appelle la fonction

// Fonction avec paramètres
function saluer($nom) {
  return "Bonjour " . $nom;
}

echo saluer("Marie"); // Affiche: "Bonjour Marie"
?>

📤 return vs echo

There is an important difference between return and echo in a function:

  • echo - Displays the result directly (cannot be retrieved)
  • return - Returns a value that you can use elsewhere (recommended)

Difference between return and echo:

<?php
// Avec echo (affiche directement)
function afficherNom($nom) {
  echo $nom; // Affiche immédiatement
}
afficherNom("Jean"); // Affiche: Jean
$resultat = afficherNom("Jean"); // $resultat vaut NULL

// Avec return (retourne une valeur)
function obtenirNom($nom) {
  return $nom; // Retourne la valeur
}
$resultat = obtenirNom("Jean"); // $resultat vaut "Jean"
echo $resultat; // Affiche: Jean
?>

📥 Function Parameters

Functions can accept multiple parameters, with or without default values.

Functions with multiple parameters:

<?php
// Fonction avec plusieurs paramètres
function presenter($prenom, $nom, $age) {
  return "Je m'appelle $prenom $nom et j'ai $age ans";
}

echo presenter("Jean", "Dupont", 30);
// Affiche: "Je m'appelle Jean Dupont et j'ai 30 ans"

// Paramètres avec valeurs par défaut
function saluer($nom, $langue = "fr") {
  if ($langue == "en") {
    return "Hello $nom";
  } else {
    return "Bonjour $nom";
  }
}

echo saluer("Marie"); // "Bonjour Marie" (utilise la valeur par défaut)
echo saluer("John", "en"); // "Hello John"
?>

🔢 Type hints and return types

Since PHP 7, you can specify parameter and return types for better security and readability.

Functions with types:

<?php
// Spécifier le type des paramètres
function additionner(int $a, int $b): int {
  return $a + $b;
}

echo additionner(5, 3); // 8

// Fonction avec type string
function majuscules(string $texte): string {
  return strtoupper($texte);
}

echo majuscules("bonjour"); // "BONJOUR"
?>

📚 Variable scope

Variables defined in a function are local to that function. To use a global variable, use the global keyword.

Variable scope:

<?php
$nom = "Jean"; // Variable globale

function afficherNom() {
  // $nom n'est pas accessible ici par défaut
  $nomLocal = "Marie"; // Variable locale
  echo $nomLocal; // "Marie"
}

// Utiliser une variable globale
function afficherNomGlobal() {
  global $nom; // Accède à la variable globale
  echo $nom; // "Jean"
}

// Meilleure pratique: passer en paramètre
function afficherNomParam($nom) {
  echo $nom; // Utilise le paramètre
}
afficherNomParam($nom); // "Jean"
?>

🎯 PHP built-in functions

PHP has thousands of built-in functions to manipulate strings, arrays, dates, files, etc.

Examples of built-in functions:

<?php
// Fonctions pour chaînes
$texte = " Bonjour Monde ";
strlen($texte); // Longueur: 15
strtoupper($texte); // " BONJOUR MONDE "
trim($texte); // "Bonjour Monde" (enlève espaces)
substr($texte, 0, 7); // "Bonjour"

// Fonctions pour tableaux
$tableau = [3, 1, 4, 2];
count($tableau); // Nombre d'éléments: 4
sort($tableau); // Trie le tableau
array_reverse($tableau); // Inverse l'ordre

// Fonctions mathématiques
abs(-5); // Valeur absolue: 5
round(3.7); // Arrondi: 4
max(1, 5, 3); // Maximum: 5
min(1, 5, 3); // Minimum: 1
?>

🎯 Practical Use Cases

Here are examples of useful functions in real-world situations:

Example 1: Calculate price with tax

<?php
function calculerTTC(float $prixHT, float $tauxTVA = 20.0): float {
  $montantTVA = $prixHT * ($tauxTVA / 100);
  return $prixHT + $montantTVA;
}

echo calculerTTC(100); // 120 (TVA 20% par défaut)
echo calculerTTC(100, 10); // 110 (TVA 10%)
?>

Example 2: Validate an email

<?php
function validerEmail(string $email): bool {
  return filter_var($email, FILTER_VALIDATE_EMAIL) !== false;
}

if (validerEmail("test@example.com")) {
  echo "Email valide";
} else {
  echo "Email invalide";
}
?>

💡 Best practice: Give descriptive names to your functions. Prefer calculatePriceWithTax() over calc(). This makes your code self-documented and easier to understand.

📚 Arrays

Arrays are data structures that allow you to store multiple values in a single variable. They are essential in PHP and are used everywhere: to store user lists, form data, database results, etc.

📋 Array Types

PHP supports two types of arrays:

  • Indexed arrays - Elements are accessible by a numeric index (0, 1, 2, ...)
  • Associative arrays - Elements are accessible by named keys ("name", "age", etc.)

🔢 Indexed Arrays

Indexed arrays use numeric indices starting at 0.

Create and use an indexed array:

<?php
// Syntaxe ancienne (PHP 5.3 et antérieur)
$fruits = array("Pomme", "Banane", "Orange");

// Syntaxe courte (PHP 5.4+) - RECOMMANDÉE
$legumes = ["Carotte", "Tomate", "Salade"];

// Accéder aux éléments (indices commencent à 0)
echo $fruits[0]; // "Pomme"
echo $fruits[1]; // "Banane"
echo $fruits[2]; // "Orange"

// Modifier un élément
$fruits[1] = "Kiwi"; // Remplace "Banane" par "Kiwi"

// Ajouter un élément
$fruits[] = "Fraise"; // Ajoute à la fin
$fruits[10] = "Mangue"; // Ajoute à l'index 10
?>

🔑 Associative Arrays

Associative arrays use named keys instead of numeric indices. This is very useful for representing structured data.

Create and use an associative array:

<?php
// Syntaxe avec array()
$personne = array(
  "nom" => "Jean",
  "prenom" => "Dupont",
  "age" => 30,
  "ville" => "Paris"
);

// Syntaxe courte (recommandée)
$etudiant = [
  "nom" => "Marie",
  "age" => 25,
  "note" => 18.5
];

// Accéder aux éléments
echo $personne["nom"]; // "Jean"
echo $personne["age"]; // 30

// Modifier un élément
$personne["age"] = 31; // Met à jour l'âge

// Ajouter un élément
$personne["email"] = "jean@example.com";
?>

🔄 Iterate Through Arrays

There are several ways to iterate through an array in PHP.

Methods to iterate through an array:

<?php
$fruits = ["Pomme", "Banane", "Orange"];

// Méthode 1: foreach (RECOMMANDÉE)
foreach ($fruits as $fruit) {
  echo $fruit . "<br>";
}

// Méthode 2: foreach avec index
foreach ($fruits as $index => $fruit) {
  echo "$index: $fruit<br>";
}

// Méthode 3: for (pour tableaux indexés)
for ($i = 0; $i < count($fruits); $i++) {
  echo $fruits[$i] . "<br>";
}
?>

🛠️ Useful Array Functions

PHP offers many functions to manipulate arrays.

Common array functions:

<?php
$nombres = [3, 1, 4, 2, 5];

// Compter les éléments
count($nombres); // 5
sizeof($nombres); // 5 (identique à count)

// Vérifier si un élément existe
in_array(3, $nombres); // true
array_key_exists(0, $nombres); // true

// Trier
sort($nombres); // [1, 2, 3, 4, 5] (modifie le tableau original)
rsort($nombres); // Tri décroissant
asort($personne); // Trie un tableau associatif par valeur
ksort($personne); // Trie par clé

// Ajouter/Supprimer des éléments
array_push($nombres, 6); // Ajoute à la fin
array_pop($nombres); // Retire le dernier
array_unshift($nombres, 0); // Ajoute au début
array_shift($nombres); // Retire le premier

// Rechercher
array_search(3, $nombres); // Retourne l'index de 3
array_keys($personne); // Retourne toutes les clés
array_values($personne); // Retourne toutes les valeurs
?>

📊 Multidimensional Arrays

An array can contain other arrays, creating multidimensional arrays. This is very useful for representing complex data structures.

Multidimensional array example:

<?php
// Tableau de personnes
$personnes = [
  [
    "nom" => "Jean",
    "age" => 30,
    "ville" => "Paris"
  ],
  [
    "nom" => "Marie",
    "age" => 25,
    "ville" => "Lyon"
  ],
  [
    "nom" => "Pierre",
    "age" => 35,
    "ville" => "Marseille"
  ]
];

// Accéder aux éléments
echo $personnes[0]["nom"]; // "Jean"
echo $personnes[1]["age"]; // 25

// Parcourir un tableau multidimensionnel
foreach ($personnes as $personne) {
  echo "{$personne['nom']} a {$personne['age']} ans et habite à {$personne['ville']}<br>";
}
?>

🎯 Practical Use Cases

Here are concrete examples of using arrays:

Example 1: Store form data

<?php
// Données d'un formulaire
$formulaire = [
  "nom" => "Jean",
  "email" => "jean@example.com",
  "age" => 30,
  "hobbies" => ["Lecture", "Sport", "Musique"]
];

// Traiter les données
foreach ($formulaire as $cle => $valeur) {
  if (is_array($valeur)) {
    echo "$cle: " . implode(", ", $valeur) . "<br>";
  } else {
    echo "$cle: $valeur<br>";
  }
}
?>

Example 2: Manipulate lists

<?php
$produits = ["Laptop", "Souris", "Clavier"];

// Ajouter un produit
$produits[] = "Écran";

// Supprimer un produit
$index = array_search("Souris", $produits);
if ($index !== false) {
  unset($produits[$index]);
}

// Réindexer le tableau après suppression
$produits = array_values($produits);

// Afficher tous les produits
foreach ($produits as $produit) {
  echo "- $produit<br>";
}
?>

💡 Best practice: Use the short syntax [] rather than array() to create arrays. It's more modern, more readable, and it's the recommended syntax since PHP 5.4.

📋 Forms

HTML forms allow users to send data to the server. PHP can retrieve and process this data via the $_GET and $_POST superglobals.

📤 GET and POST Methods

There are two main methods for sending data from a form:

  • GET - Data is visible in the URL (limited to ~2000 characters). Used for searches, filters, etc.
  • POST - Data is sent securely (not visible in the URL). Used for login forms, registration, etc.

📥 Retrieve POST Data

Data sent via POST is accessible via the $_POST superglobal.

Form example with POST:

<!-- Formulaire HTML -->
<form method="POST" action="traitement.php">
  <input type="text" name="nom" placeholder="Votre nom" required>
  <input type="email" name="email" placeholder="Votre email" required>
  <button type="submit">Envoyer</button>
</form>

// traitement.php - Récupérer les données
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // Récupérer les données
  $nom = $_POST["nom"] ?? ''; // Utilise ?? pour valeur par défaut
  $email = $_POST["email"] ?? '';

  // Valider les données
  if (!empty($nom) && !empty($email)) {
    echo "Bonjour $nom, votre email est $email";
  } else {
    echo "Veuillez remplir tous les champs";
  }
}
?>

📥 Retrieve GET Data

Data sent via GET is accessible via the $_GET superglobal and appears in the URL.

Example with GET:

// URL: recherche.php?q=php&categorie=web
<?php
// Récupérer les paramètres GET
$recherche = $_GET["q"] ?? ''; // "php"
$categorie = $_GET["categorie"] ?? ''; // "web"

if (!empty($recherche)) {
  echo "Résultats pour: $recherche dans la catégorie $categorie";
}
?>

🔒 Security and Validation

It is crucial to validate and secure form data to prevent attacks (XSS, SQL injection, etc.).

Validation and security:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  // Récupérer et nettoyer les données
  $nom = trim($_POST["nom"] ?? ''); // Enlève les espaces
  $email = filter_var($_POST["email"] ?? '', FILTER_SANITIZE_EMAIL);
  $message = htmlspecialchars($_POST["message"] ?? '', ENT_QUOTES, 'UTF-8');

  // Valider
  $erreurs = [];

  if (empty($nom)) {
    $erreurs[] = "Le nom est requis";
} elseif (strlen($nom) < 2) {
    $erreurs[] = "Le nom doit contenir au moins 2 caractères";
}

  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $erreurs[] = "Email invalide";
}

  if (empty($erreurs)) {
    // Traiter les données (envoyer email, sauvegarder en BDD, etc.)
    echo "Formulaire validé avec succès !";
} else {
    // Afficher les erreurs
    foreach ($erreurs as $erreur) {
      echo "Erreur: $erreur<br>";
    }
  }
}
?>

📋 Complete Form Example

Here is a complete example with HTML form and PHP processing on the same page:

Complete form:

<?php
$message = '';
$erreur = '';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $nom = trim($_POST["nom"] ?? '');
  $email = filter_var($_POST["email"] ?? '', FILTER_SANITIZE_EMAIL);

  if (empty($nom)) {
    $erreur = "Le nom est requis";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $erreur = "Email invalide";
} else {
    $message = "Merci $nom, votre formulaire a été envoyé !";
    // Ici vous pourriez envoyer un email, sauvegarder en BDD, etc.
  }
}
?>

<!DOCTYPE html>
<html>
<head>
  <title>Formulaire de contact</title>
</head>
<body>
  <?php if ($message): ?>
    <p style="color: green;"><?php echo $message; ?></p>
  <?php endif; ?>

  <?php if ($erreur): ?>
    <p style="color: red;"><?php echo $erreur; ?></p>
  <?php endif; ?>

  <form method="POST" action="">
    <input type="text" name="nom" placeholder="Nom" required>
    <input type="email" name="email" placeholder="Email" required>
    <button type="submit">Envoyer</button>
  </form>
</body>
</html>

⚠️ Important security: Always validate and sanitize form data! Use htmlspecialchars() to prevent XSS attacks, filter_var() to validate emails, and prepared statements for databases (see PDO section).

🔐 Sessions

Sessions allow you to store user information between web pages. Unlike cookies which are stored client-side, sessions are stored server-side, making them more secure for storing sensitive data.

🌐 How do sessions work?

When you start a session, PHP creates a unique identifier (session ID) that is sent to the browser as a cookie. This cookie allows the server to recognize the user on subsequent requests and retrieve their session data.

▶️ Start a Session

Before using sessions, you must call session_start() at the beginning of each PHP page that uses sessions.

Start and use a session:

<?php
// Démarrer la session (doit être appelé avant tout output HTML)
session_start();

// Stocker des données dans la session
$_SESSION["username"] = "Jean";
$_SESSION["email"] = "jean@example.com";
$_SESSION["role"] = "admin";
$_SESSION["login_time"] = time(); // Timestamp actuel

// Récupérer des données de la session
echo "Bonjour " . $_SESSION["username"]; // "Bonjour Jean"

// Vérifier si une variable de session existe
if (isset($_SESSION["username"])) {
  echo "Utilisateur connecté: " . $_SESSION["username"];
}
?>

🗑️ Delete Session Data

You can delete individual variables or completely destroy the session.

Delete session data:

<?php
session_start();

// Supprimer une variable spécifique
unset($_SESSION["username");

// Supprimer toutes les variables de session
$_SESSION = []; // Vide le tableau

// Détruire complètement la session
session_destroy(); // Détruit la session côté serveur
// Note: session_destroy() ne supprime pas le cookie, il faut aussi:
if (ini_get("session.use_cookies")) {
  $params = session_get_cookie_params();
  setcookie(session_name(), '', time() - 42000,
    $params["path"], $params["domain"],
    $params["secure"], $params["httponly"]
  );
}
?>

🔐 Example: Login System

Here is a complete example of using sessions for a login system:

Login system with sessions:

// login.php - Page de connexion
<?php
session_start();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $username = $_POST["username"] ?? '';
  $password = $_POST["password"] ?? '';

  // Vérifier les identifiants (exemple simplifié)
  if ($username == "admin" && $password == "secret123") {
    // Créer la session
    $_SESSION["logged_in"] = true;
    $_SESSION["username"] = $username;
    $_SESSION["login_time"] = time();

    // Rediriger vers la page d'accueil
    header("Location: index.php");
    exit;
  } else {
    $erreur = "Identifiants incorrects";
  }
}
?>

// index.php - Page protégée
<?php
session_start();

// Vérifier si l'utilisateur est connecté
if (!isset($_SESSION["logged_in"]) || !$_SESSION["logged_in"]) {
  // Rediriger vers la page de connexion
  header("Location: login.php");
  exit;
}

echo "Bienvenue " . $_SESSION["username"] . " !";
?>

// logout.php - Déconnexion
<?php
session_start();
$_SESSION = []; // Vider la session
session_destroy(); // Détruire la session
header("Location: login.php");
exit;
?>

⏱️ Session Lifetime

By default, a PHP session expires after 24 minutes of inactivity. You can modify this duration in the php.ini file or with ini_set().

Configure session lifetime:

<?php
// Modifier la durée de vie de la session (en secondes)
ini_set('session.gc_maxlifetime', 3600); // 1 heure
session_set_cookie_params(3600); // Cookie expire après 1 heure
session_start();
?>

⚠️ Important: <code>session_start()</code> must be called before any HTML output (even a space or blank line). Otherwise, you will get the "Headers already sent" error.

🗄️ MySQL

MySQL is one of the most popular relational database management systems (RDBMS). PHP can connect to MySQL to store, retrieve, modify and delete data. There are two main extensions: MySQLi (improved) and PDO (more modern and recommended).

🔌 Connect to MySQL with MySQLi

MySQLi (MySQL Improved) is the improved MySQL extension. It supports prepared statements and offers better performance.

Connexion et requêtes de base :

<?php
// Connexion à la base de données
$host = "localhost";
$username = "root";
$password = ""; // Mot de passe vide par défaut (XAMPP)
$database = "ma_base";

$conn = mysqli_connect($host, $username, $password, $database);

// Vérifier la connexion
if (!$conn) {
  die("Connexion échouée: " . mysqli_connect_error());
}
echo "Connexion réussie !";

// Fermer la connexion
mysqli_close($conn);
?>

📖 SELECT Query (Read Data)

The SELECT query allows you to retrieve data from the database.

SELECT query example:

<?php
$conn = mysqli_connect("localhost", "root", "", "ma_base");

// Requête SELECT
$sql = "SELECT id, nom, email FROM users";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
  // Parcourir les résultats
  while ($row = mysqli_fetch_assoc($result)) {
    echo "ID: " . $row["id"] . ", Nom: " . $row["nom"] . ", Email: " . $row["email"] . "<br>";
  }
} else {
  echo "Aucun résultat trouvé";
}

mysqli_close($conn);
?>

➕ INSERT Query (Add Data)

The INSERT query allows you to add new data to the database.

INSERT query example:

<?php
$conn = mysqli_connect("localhost", "root", "", "ma_base");

// Données à insérer
$nom = "Jean Dupont";
$email = "jean@example.com";
$age = 30;

// Requête INSERT (⚠️ DANGEREUX - voir section PDO pour requêtes préparées)
$sql = "INSERT INTO users (nom, email, age) VALUES ('$nom', '$email', $age)";

if (mysqli_query($conn, $sql)) {
  echo "Nouvel utilisateur créé avec succès. ID: " . mysqli_insert_id($conn);
} else {
  echo "Erreur: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

✏️ UPDATE Query (Modify Data)

The UPDATE query allows you to modify existing data.

UPDATE query example:

<?php
$conn = mysqli_connect("localhost", "root", "", "ma_base");

$id = 1;
$nouveauNom = "Marie Martin";
$nouvelAge = 25;

$sql = "UPDATE users SET nom='$nouveauNom', age=$nouvelAge WHERE id=$id";

if (mysqli_query($conn, $sql)) {
  echo "Utilisateur mis à jour. Lignes affectées: " . mysqli_affected_rows($conn);
} else {
  echo "Erreur: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

🗑️ DELETE Query (Delete Data)

The DELETE query allows you to delete data from the database.

DELETE query example:

<?php
$conn = mysqli_connect("localhost", "root", "", "ma_base");

$id = 1;
$sql = "DELETE FROM users WHERE id=$id";

if (mysqli_query($conn, $sql)) {
  echo "Utilisateur supprimé avec succès";
} else {
  echo "Erreur: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

⚠️ CRITICAL Security: The examples above use direct queries that are vulnerable to SQL injection attacks! NEVER use this method in production. Always use prepared statements (see PDO section below) to protect your application.

🔌 PDO

PDO (PHP Data Objects) is a modern and secure interface for accessing databases. It is the recommended method for working with databases in PHP because it offers:

  • ✅ Sécurité - Protection against SQL injection via prepared statements
  • ✅ Portabilité - Works with MySQL, PostgreSQL, SQLite, etc.
  • ✅ Simplicité - Consistent API for all databases
  • ✅ Performance - Better performance than MySQLi

🔌 Connect with PDO

PDO connection uses a DSN (Data Source Name) to specify the database.

PDO Connection:

<?php
try {
  // Connexion avec gestion d'erreurs
  $pdo = new PDO(
    "mysql:host=localhost;dbname=ma_base;charset=utf8mb4",
    "root", // Username
    "", // Password
    [
      PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
      PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
    ]
  );
  echo "Connexion réussie !";
} catch (PDOException $e) {
  echo "Erreur de connexion: " . $e->getMessage();
}
?>

🔒 Prepared Statements (Secure)

Prepared statements are the best way to protect your application against SQL injection. Values are separated from the SQL query itself.

SELECT with prepared statement:

<?php
$pdo = new PDO("mysql:host=localhost;dbname=ma_base", "root", "");

// Requête préparée avec paramètres nommés (recommandé)
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id AND email = :email");
$stmt->execute([
  'id' => 1,
  'email' => 'jean@example.com'
]);

// Récupérer les résultats
$user = $stmt->fetch(); // Un seul résultat
// ou
$users = $stmt->fetchAll(); // Tous les résultats

if ($user) {
  echo "Nom: " . $user['nom'];
}
?>

INSERT with prepared statement:

<?php
$pdo = new PDO("mysql:host=localhost;dbname=ma_base", "root", "");

$nom = "Jean Dupont";
$email = "jean@example.com";
$age = 30;

// Requête préparée INSERT
$stmt = $pdo->prepare("INSERT INTO users (nom, email, age) VALUES (:nom, :email, :age)");
$stmt->execute([
  'nom' => $nom,
  'email' => $email,
  'age' => $age
]);

echo "Utilisateur créé. ID: " . $pdo->lastInsertId();
?>

UPDATE and DELETE with prepared statements:

<?php
$pdo = new PDO("mysql:host=localhost;dbname=ma_base", "root", "");

// UPDATE
$stmt = $pdo->prepare("UPDATE users SET nom = :nom, age = :age WHERE id = :id");
$stmt->execute([
  'id' => 1,
  'nom' => "Marie Martin",
  'age' => 25
]);
echo "Lignes modifiées: " . $stmt->rowCount();

// DELETE
$stmt = $pdo->prepare("DELETE FROM users WHERE id = :id");
$stmt->execute(['id' => 1]);
echo "Lignes supprimées: " . $stmt->rowCount();
?>

🔄 Iterate Through Multiple Results

You can iterate through query results in several ways.

Methods to retrieve results:

<?php
$pdo = new PDO("mysql:host=localhost;dbname=ma_base", "root", "");
$stmt = $pdo->prepare("SELECT * FROM users");
$stmt->execute();

// Méthode 1: fetchAll() - Récupère tous les résultats
$users = $stmt->fetchAll();
foreach ($users as $user) {
  echo $user['nom'] . "<br>";
}

// Méthode 2: fetch() dans une boucle - Récupère un par un
while ($user = $stmt->fetch()) {
  echo $user['nom'] . "<br>";
}
?>

✅ Advantage of prepared statements: Prepared statements automatically protect against SQL injection. Values are treated as data, not as SQL code. This is the mandatory method to use in production!

🏗️ Object-Oriented Programming (OOP)

Object-Oriented Programming (OOP) is a programming paradigm that organizes code into classes and objects. It allows you to create reusable, maintainable and modular code structures. OOP is essential for developing modern and complex PHP applications.

📚 Fundamental Concepts

OOP is based on several key concepts:

  • Class - A model or blueprint for creating objects (like a mold)
  • Object - A concrete instance of a class (like a cake made with the mold)
  • Property - A variable belonging to a class or object
  • Method - A function belonging to a class or object
  • Encapsulation - The principle of hiding internal details and exposing only what is necessary
  • Inheritance - The ability of a class to inherit properties and methods from another class

🏗️ Create a Class

A class is defined with the class keyword followed by the class name.

Simple class example:

<?php
class Personne {
  // Propriétés (variables de la classe)
  public $nom;
  public $prenom;
  private $age; // private = accessible uniquement dans la classe

  // Constructeur - appelé lors de la création d'un objet
  public function __construct($nom, $prenom, $age) {
    $this->nom = $nom;
    $this->prenom = $prenom;
    $this->age = $age;
  }

  // Méthode (fonction de la classe)
  public function saluer() {
    return "Bonjour, je suis $this->prenom $this->nom";
  }

  // Méthode pour accéder à une propriété privée
  public function getAge() {
    return $this->age;
  }
}

// Créer un objet (instance de la classe)
$personne1 = new Personne("Dupont", "Jean", 30);
$personne2 = new Personne("Martin", "Marie", 25);

// Utiliser les méthodes
echo $personne1->saluer(); // "Bonjour, je suis Jean Dupont"
echo $personne1->nom; // "Dupont" (propriété publique)
echo $personne1->getAge(); // 30 (via méthode)
// echo $personne1->age; // ERREUR: propriété privée
?>

🔒 Property and Method Visibility

PHP offers three levels of visibility to control access to properties and methods:

  • public - Accessible everywhere (in the class, in child classes, and from outside)
  • private - Accessible only within the class itself
  • protected - Accessible in the class and its child classes (inheritance)

Visibility example:

<?php
class Exemple {
  public $public = "Accessible partout";
  private $private = "Accessible uniquement ici";
  protected $protected = "Accessible ici et dans les enfants";

  public function afficherPrivate() {
    return $this->private; // OK: dans la classe
  }
}

$obj = new Exemple();
echo $obj->public; // OK: public
// echo $obj->private; // ERREUR: private
// echo $obj->protected; // ERREUR: protected
echo $obj->afficherPrivate(); // OK: via méthode publique
?>

🏗️ Constructor and Destructor

The constructor (__construct) is automatically called when an object is created. The destructor (__destruct) is called when the object is destroyed.

Constructor and destructor:

<?php
class Utilisateur {
  private $nom;
  private $email;

  // Constructeur
  public function __construct($nom, $email) {
    $this->nom = $nom;
    $this->email = $email;
    echo "Utilisateur créé: $nom<br>";
  }

  // Destructeur
  public function __destruct() {
    echo "Utilisateur détruit: {$this->nom}<br>";
  }

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

$user = new Utilisateur("Jean", "jean@example.com");
// Affiche: "Utilisateur créé: Jean"
echo $user->getNom(); // "Jean"
// Quand $user est détruit, affiche: "Utilisateur détruit: Jean"
?>

🔧 Getters and Setters

Getters and setters are methods to access and modify private properties. This is a good practice that allows you to control data access.

Getters and Setters:

<?php
class Produit {
  private $nom;
  private $prix;

  public function __construct($nom, $prix) {
    $this->setNom($nom);
    $this->setPrix($prix);
  }

  // Getter pour nom
  public function getNom() {
    return $this->nom;
  }

  // Setter pour nom (avec validation)
  public function setNom($nom) {
    if (strlen($nom) < 2) {
      throw new Exception("Le nom doit contenir au moins 2 caractères");
    }
    $this->nom = $nom;
  }

  // Getter pour prix
  public function getPrix() {
    return $this->prix;
  }

  // Setter pour prix (avec validation)
  public function setPrix($prix) {
    if ($prix < 0) {
      throw new Exception("Le prix ne peut pas être négatif");
    }
    $this->prix = $prix;
  }
}

$produit = new Produit("Laptop", 999.99);
echo $produit->getNom(); // "Laptop"
echo $produit->getPrix(); // 999.99
$produit->setPrix(899.99); // Modifier le prix
?>

👨‍👩‍👧‍👦 Inheritance

Inheritance allows a class (child) to inherit properties and methods from another class (parent). This is very useful for avoiding code duplication.

Inheritance example:

<?php
// Classe parent
class Animal {
  protected $nom;
  protected $espece;

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

  public function manger() {
    return "{$this->nom} mange";
  }

  public function dormir() {
    return "{$this->nom} dort";
  }
}

// Classe enfant (hérite de Animal)
class Chien extends Animal {
  public function __construct($nom) {
    parent::__construct($nom, "Chien"); // Appeler le constructeur parent
  }

  // Méthode spécifique au chien
  public function aboyer() {
    return "{$this->nom} aboie: Wouf Wouf !";
  }
}

// Classe enfant (hérite de Animal)
class Chat extends Animal {
  public function __construct($nom) {
    parent::__construct($nom, "Chat");
  }

  // Méthode spécifique au chat
  public function miauler() {
    return "{$this->nom} miaule: Miaou !";
  }
}

// Utilisation
$chien = new Chien("Rex");
$chat = new Chat("Mimi");

echo $chien->manger(); // "Rex mange" (hérité)
echo $chien->aboyer(); // "Rex aboie: Wouf Wouf !" (spécifique)
echo $chat->dormir(); // "Mimi dort" (hérité)
echo $chat->miauler(); // "Mimi miaule: Miaou !" (spécifique)
?>

🎯 Static Methods

Static methods belong to the class itself, not to an instance. They are called with ClassName::methodName().

Static methods:

<?php
class Calculatrice {
  // Méthode statique
  public static function additionner($a, $b) {
    return $a + $b;
  }

  public static function multiplier($a, $b) {
    return $a * $b;
  }
}

// Appeler sans créer d'objet
echo Calculatrice::additionner(5, 3); // 8
echo Calculatrice::multiplier(4, 7); // 28
?>

🎯 Practical Use Case: User Management

Here is a complete example using OOP to manage users:

User management system:

<?php
class Utilisateur {
  private $id;
  private $nom;
  private $email;
  private $role;

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

  public function getNom() { return $this->nom; }
  public function getEmail() { return $this->email; }
  public function getRole() { return $this->role; }

  public function estAdmin() {
    return $this->role === "admin";
  }

  public function presenter() {
    return "Je suis {$this->nom} ({$this->email}), rôle: {$this->role}";
  }
}

$user1 = new Utilisateur("Jean", "jean@example.com");
$admin = new Utilisateur("Admin", "admin@example.com", "admin");

echo $user1->presenter(); // "Je suis Jean (jean@example.com), rôle: user"
echo $admin->estAdmin(); // true
?>

💡 Best practice: Use OOP to organize your code into logical structures. Classes allow you to group related functionality, reuse code through inheritance, and protect data with encapsulation. This is essential for developing professional PHP applications!

🎓 Next Steps

Congratulations! You now have a solid foundation in PHP.

✅ What you learned:

  • PHP syntax and variables
  • Data types
  • Operators and expressions
  • Conditional structures
  • Loops
  • Functions
  • Arrays
  • Form handling
  • Sessions and cookies
  • MySQL connection
  • PDO and prepared statements
  • Object-Oriented Programming
Cliquer pour discuter avec NiangProgrammeur
NiangProgrammeur
En ligne

Bonjour ! 👋

Comment puis-je vous aider aujourd'hui ?