PHP : premiers pas
Exécuter du PHP
Section intitulée « Exécuter du PHP »php -r 'echo "Bonjour\n";' # une lignephp bonjour.php # un fichierphp -a # console interactivephp -S 127.0.0.1:8000 -t public # serveur de développementFichier bonjour.php :
<?phpdeclare(strict_types=1);
$nom = $argv[1] ?? 'monde';echo "Bonjour, {$nom} !\n";php bonjour.php Alicedeclare(strict_types=1) active le typage strict pour le fichier : à placer en tête de chaque fichier.
Variables et types
Section intitulée « Variables et types »<?php$entier = 42;$decimal = 3.14;$texte = 'chaîne';$actif = true;$rien = null;
echo gettype($entier), "\n"; // integervar_dump($decimal); // float(3.14)echo "Valeur : $entier et {$texte}\n"; // interpolation (guillemets doubles)Tableaux
Section intitulée « Tableaux »<?php$liste = ['a', 'b', 'c'];$liste[] = 'd';$personne = ['nom' => 'Alice', 'age' => 30];
echo count($liste), "\n";echo $personne['nom'], "\n";
foreach ($liste as $i => $valeur) { echo "$i : $valeur\n";}foreach ($personne as $cle => $valeur) { echo "$cle = $valeur\n";}
$carres = array_map(fn (int $n): int => $n * $n, [1, 2, 3]);$pairs = array_filter([1, 2, 3, 4], fn (int $n): bool => $n % 2 === 0);print_r($carres);Conditions et boucles
Section intitulée « Conditions et boucles »<?php$age = 20;if ($age >= 18) { echo "majeur\n";} elseif ($age >= 16) { echo "presque\n";} else { echo "mineur\n";}
$statut = match (true) { $age >= 18 => 'majeur', default => 'mineur',};
for ($i = 1; $i <= 3; $i++) { echo $i, "\n";}Comparer avec === (valeur et type) plutôt qu’avec ==, qui convertit les types.
Fonctions
Section intitulée « Fonctions »<?phpdeclare(strict_types=1);
function additionner(int $a, int $b = 0): int{ return $a + $b;}
echo additionner(2, 3), "\n";echo additionner(b: 5, a: 1), "\n"; // arguments nommés<?phpdeclare(strict_types=1);
final class Client{ public function __construct( public readonly string $nom, private string $email, ) {}
public function email(): string { return $this->email; }}
$c = new Client('Alice', 'alice@exemple.com');echo $c->nom, ' ', $c->email(), "\n";Erreurs et exceptions
Section intitulée « Erreurs et exceptions »<?phptry { $resultat = intdiv(1, 0);} catch (DivisionByZeroError $e) { fwrite(STDERR, 'Erreur : ' . $e->getMessage() . "\n"); exit(1);} finally { echo "terminé\n";}Fichiers et JSON
Section intitulée « Fichiers et JSON »<?php$contenu = file_get_contents('donnees.json');$donnees = json_decode($contenu, true, flags: JSON_THROW_ON_ERROR);file_put_contents('sortie.json', json_encode($donnees, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE));Arguments en ligne de commande
Section intitulée « Arguments en ligne de commande »<?php$options = getopt('n:v', ['nom:', 'verbeux']);var_dump($options);php script.php -n Alice --verbeuxDépannage
Section intitulée « Dépannage »| Symptôme | Piste |
|---|---|
| Page blanche | Erreur masquée : voir Configuration (display_errors, journal) |
Parse error: syntax error |
Syntaxe : le message indique la ligne |
Undefined variable / Undefined array key |
Variable ou clé inexistante : tester avec isset() ou ?? |
Call to undefined function mb_strlen() |
Extension manquante : sudo apt install php-mbstring |
Ubuntu 24.04 et 26.04 : différences à connaître
Section intitulée « Ubuntu 24.04 et 26.04 : différences à connaître »Le code de cette page fonctionne en PHP 8.3 et 8.5.
Pour aller plus loin
Section intitulée « Pour aller plus loin »- Manuel PHP
- Suite : Composer