<?php
function greet() {
return "Hello, World!";
}
// 1. Exécute la fonction `greet()`
// 2. Récupère la valeur de retour
// 3. Affecte (= donne) cette valeur à la variable `$greetings`
$greetings = greet();
// Affiche le résultat ("Hello, World!")
echo $greetings;
<?php
function greet($name) {
return "Hello, " . $name . "!";
}
$greetings = greet("Alice");
echo $greetings . "<br>"; // "Hello, Alice!"
echo greet("Bob") . "<br>"; // "Hello, Bob!"
<?php
function greet($name = "World") {
return "Hello, " . $name . "!";
}
echo greet() . "<br>"; // "Hello, World!" (utilise la valeur par défaut)
echo greet("Alice") . "<br>"; // "Hello, Alice!" (utilise l'argument fourni)
<?php
function greet(string $name = "World"): string {
return "Hello, " . $name . "!";
}
function add(int $a, int $b): int {
return $a + $b;
}
echo greet() . "<br>"; // "Hello, World!"
echo greet("Alice") . "<br>"; // "Hello, Alice!"
echo greet(42) . "<br>"; // "Hello, 42!" (conversion implicite)
echo add(2, 3) . "<br>"; // 5
// Erreur 1 : Implicit conversion from float 2.5 to int loses precision
// Erreur 2 : Argument #2 ($b) must be of type int, string given
echo add(2.5, "Hello") . "<br>";
require
(erreur et arrête l'exécution) plutôt
que include
(avertissement mais continue l'exécution).<?php
// Fichier functions.php
function greet(string $name = "World"): string {
return "Hello, " . $name . "!";
}
<?php
// Fichier index.php
require "functions.php";
echo greet("Alice"); // "Hello, Alice!"
[]
) ou avec la fonction
array()
.<?php
// Tableau indexé numériquement
$fruits = ['apple', 'banana', 'orange'];
echo $fruits[0] . "<br>"; // "apple"
// Tableau associatif
$person = [
'name' => 'Alice',
'age' => 30,
'city' => 'New York'
];
echo $person['name'] . "<br>"; // "Alice"
for
, while
, do...while
et
foreach
.<?php
// Affiche les nombres de 0 à 9
for ($i = 0; $i < 10; $i++) {
echo "$i<br>";
}
<?php
$i = 0;
// Affiche les nombres de 0 à 9
while ($i < 10) {
echo "$i<br>";
$i++;
}
<?php
$randomNumber = null;
do {
// La fonction `rand()` génère un nombre aléatoire entre 1 et 10
$randomNumber = rand(1, 10);
echo "The random number is $randomNumber<br>";
} while ($randomNumber < 8);
<?php
$users = [
'john' => [
'name' => 'John Doe',
'age' => 30,
'city' => 'New York',
],
'jane' => [
'name' => 'Jane Doe',
'age' => 25,
'city' => 'Los Angeles',
],
];
// `$user` contient la valeur de l'élément du tableau
foreach ($users as $user) {
echo "Name: {$user['name']}<br>";
echo "Age: {$user['age']}<br>";
echo "City: {$user['city']}<br>";
echo "<br>";
}
$_POST
et
$_GET
.<?php
class User {
// Propriétés (attributs)
private string $firstName;
private string $lastName;
// Constructeur
public function __construct(string $firstName, string $lastName) {
$this->firstName = $firstName;
$this->lastName = $lastName;
}
// Méthodes
public function getFirstName(): string {
return $this->firstName;
}
public function setFirstName(string $firstName): void {
$this->firstName = $firstName;
}
public function getLastName(): string {
return $this->lastName;
}
public function setLastName(string $lastName): void {
$this->lastName = $lastName;
}
public function getFullName(): string {
return "{$this->firstName} {$this->lastName}";
}
}
// Création d'objets (instanciation)
$user1 = new User("Alice", "Smith");
$user2 = new User("Bob", "Johnson");
// Utilisation des méthodes
echo $user1->getFirstName() . "<br>"; // "Alice"
echo $user2->getFullName() . "<br>"; // "Bob Johnson"
$user2->setLastName("Doe"); // Modifie le nom de famille de Bob
echo $user2->getFullName() . "<br>"; // "Bob Doe"
<?php
interface AnimalInterface {
public function makeSound(): string;
public function getHabitat(): string;
}
class Lion implements AnimalInterface {
public function makeSound(): string {
return "Roar!";
}
public function getHabitat(): string {
return "Savannah";
}
}
class Penguin implements AnimalInterface {
public function makeSound(): string {
return "Honk!";
}
public function getHabitat(): string {
return "Antarctica";
}
}
$lion = new Lion();
$penguin = new Penguin();
echo $lion->makeSound(); // "Roar!"
echo $lion->getHabitat(); // "Savannah"
echo $penguin->makeSound(); // "Honk!"
echo $penguin->getHabitat(); // "Antarctica"
<?php
class Plant {
protected string $englishName;
protected string $latinName;
public function __construct(string $englishName, string $latinName) {
$this->englishName = $englishName;
$this->latinName = $latinName;
}
public function getEnglishName(): string {
return $this->englishName;
}
public function getLatinName(): int {
return $this->latinName;
}
}
class Basil extends Plant {
private string $variety;
public function __construct(string $englishName, string $latinName, string $variety) {
parent::__construct($englishName, $latinName);
$this->variety = $variety;
}
public function getVariety(): string {
return $this->variety;
}
}
class Tomato extends Plant {
private string $color;
public function __construct(string $englishName, string $latinName, string $color) {
parent::__construct($englishName, $latinName);
$this->color = $color;
}
public function getColor(): string {
return $this->color;
}
}
$plant = new Plant("Generic Plant", "Plantae");
$basil = new Basil("Basil", "Ocimum basilicum", "Sweet Basil");
$tomato = new Tomato("Tomato", "Solanum lycopersicum", "Red");
echo $plant->getEnglishName(); // "Generic Plant"
echo $plant->getLatinName(); // "Plantae"
echo $basil->getVariety(); // "Sweet Basil"
echo $tomato->getColor(); // "Red"
<?php
abstract class Shape {
protected string $color;
public function __construct(string $color) {
$this->color = $color;
}
// Méthode concrète (implémentée)
public function getColor(): string {
return $this->color;
}
// Méthodes abstraites (doivent être implémentées par les classes filles)
abstract public function calculateArea(): float;
abstract public function calculatePerimeter(): float;
// Méthode concrète utilisant les méthodes abstraites
public function getShapeInfo(): string {
return sprintf(
"Shape: %s, Color: %s, Area: %.2f, Perimeter: %.2f",
static::class,
$this->color,
$this->calculateArea(),
$this->calculatePerimeter()
);
}
}
class Rectangle extends Shape {
private float $width;
private float $height;
public function __construct(string $color, float $width, float $height) {
parent::__construct($color);
$this->width = $width;
$this->height = $height;
}
public function calculateArea(): float {
return $this->width * $this->height;
}
public function calculatePerimeter(): float {
return 2 * ($this->width + $this->height);
}
}
class Circle extends Shape {
private float $radius;
public function __construct(string $color, float $radius) {
parent::__construct($color);
$this->radius = $radius;
}
public function calculateArea(): float {
return pi() * pow($this->radius, 2);
}
public function calculatePerimeter(): float {
return 2 * pi() * $this->radius;
}
}
$rectangle = new Rectangle("blue", 10, 5);
$circle = new Circle("red", 7);
echo $rectangle->getShapeInfo();
// Shape: Rectangle, Color: blue, Area: 50.00, Perimeter: 30.00
echo $circle->getShapeInfo();
// Shape: Circle, Color: red, Area: 153.94, Perimeter: 43.98
$shape = new Shape("green"); // Erreur fatale : Cannot instantiate abstract class Shape
require
ou include
.require_once
ou include_once
pour éviter les
inclusions multiples.<?php
// Animal.php
abstract class Animal {
protected string $name;
protected float $size;
public function __construct(string $name, float $size) {
$this->name = $name;
$this->size = $size;
}
abstract public function makeSound(): string;
public function getName(): string {
return $this->name;
}
public function setName(string $name): void {
$this->name = $name;
}
public function getSize(): float {
return $this->size;
}
public function setSize(float $size): void {
$this->size = $size;
}
}
<?php
// Pet.php
require 'Animal.php';
abstract class Pet extends Animal {
protected string $nickname;
public function __construct(string $name, float $size, string $nickname) {
parent::__construct($name, $size);
$this->nickname = $nickname;
}
public function getNickname(): string {
return $this->nickname;
}
public function setNickname(string $nickname): void {
$this->nickname = $nickname;
}
}
<?php
// Dog.php
require 'Pet.php';
class Dog extends Pet {
public function __construct(string $name, float $size, string $nickname) {
parent::__construct($name, $size, $nickname);
}
public function makeSound(): string {
return "Woof!";
}
}
<?php
// Cat.php
require 'Pet.php';
class Cat extends Pet {
public function __construct(string $name, float $size, string $nickname) {
parent::__construct($name, $size, $nickname);
}
public function makeSound(): string {
return "Meow!";
}
}
<?php
// index.php
require 'Dog.php';
require 'Cat.php';
$dog = new Dog("Nalia", 30.5, "Naliouille");
$cat = new Cat("Tofu", 10.0, "Sushi");
echo $dog->getName() . " says: " . $dog->makeSound() . "<br>";
echo $cat->getName() . " says: " . $cat->makeSound() . "<br>";
<?php
// Dog.php
require_once 'Pet.php';
...
<?php
// Cat.php
require_once 'Pet.php';
...
<?php
// Pet.php
require_once 'Animal.php';
...
namespace
au début d'un fichier.<?php
// src/Animals/Animal.php
namespace Animals;
abstract class Animal {
protected string $name;
// ...
}
<?php
// src/Animals/Pets/Pet.php
namespace Animals\Pets;
require_once 'Animal.php';
use Animals\Animal;
abstract class Pet extends Animal {
protected string $nickname;
// ...
}
<?php
// src/Animals/Pets/Dog.php
namespace Animals\Pets;
require_once 'Pet.php';
use Animals\Pets\Pet;
class Dog extends Pet {
// ...
}
<?php
// src/Animals/Pets/Cat.php
namespace Animals\Pets;
require_once 'Pet.php';
use Animals\Pets\Pet;
class Cat extends Pet {
// ...
}
<?php
// autoloader.php
// Charge les classes automatiquement
spl_autoload_register(function ($class) {
// Convertit les séparateurs de namespace en séparateurs de répertoires
$relativePath = str_replace('\\', '/', $class);
// Construit le chemin complet du fichier
$file = __DIR__ . '/../classes/' . $relativePath . '.php';
// Vérifie si le fichier existe avant de l'inclure
if (file_exists($file)) {
// Inclut le fichier de classe
require_once $file;
}
});
<?php
// index.php
require 'autoloader.php'; // Plus besoin d'inclure chaque fichier de classe manuellement
use Animals\Pets\Dog;
use Animals\Pets\Cat;
$dog = new Dog("Nalia", 30.5, "Naliouille");
$cat = new Cat("Tofu", 10.0, "Sushi");
echo $dog->getName() . " says: " . $dog->makeSound() . "<br>";
echo $cat->getName() . " says: " . $cat->makeSound() . "<br>";
Est-ce que vous avez des questions ?
N'hésitez pas à vous entraidez si vous avez des difficultés !
URLs
Illustrations