Aller au contenu

PHP : premiers pas

Fenêtre de terminal
php -r 'echo "Bonjour\n";' # une ligne
php bonjour.php # un fichier
php -a # console interactive
php -S 127.0.0.1:8000 -t public # serveur de développement

Fichier bonjour.php :

<?php
declare(strict_types=1);
$nom = $argv[1] ?? 'monde';
echo "Bonjour, {$nom} !\n";
Fenêtre de terminal
php bonjour.php Alice

declare(strict_types=1) active le typage strict pour le fichier : à placer en tête de chaque fichier.

<?php
$entier = 42;
$decimal = 3.14;
$texte = 'chaîne';
$actif = true;
$rien = null;
echo gettype($entier), "\n"; // integer
var_dump($decimal); // float(3.14)
echo "Valeur : $entier et {$texte}\n"; // interpolation (guillemets doubles)
<?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);
<?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.

<?php
declare(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
<?php
declare(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";
<?php
try {
$resultat = intdiv(1, 0);
} catch (DivisionByZeroError $e) {
fwrite(STDERR, 'Erreur : ' . $e->getMessage() . "\n");
exit(1);
} finally {
echo "terminé\n";
}
<?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));
<?php
$options = getopt('n:v', ['nom:', 'verbeux']);
var_dump($options);
Fenêtre de terminal
php script.php -n Alice --verbeux
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.