Last active
September 18, 2021 10:01
-
-
Save alexsoyes/e81f13c75bec17d1a36f8df0685f34fd to your computer and use it in GitHub Desktop.
Cours PHP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$students = [ | |
[ | |
'firstname' => 'Alex', | |
'age' => 27, | |
], | |
[ | |
'firstname' => 'Bastien', | |
'age' => 19, | |
], | |
[ | |
'firstname' => 'Carolina', | |
'age' => 47, | |
], | |
]; | |
$numberOfStudents = count( $students ); | |
// parcourir du plus petit au plus grand | |
for ( $i = 0; $i < $numberOfStudents; $i ++ ) { | |
printf( "L'étudiant %s a %d ans !", $students[ $i ]['firstname'], $students[ $i ]['age'] ); | |
} | |
// parcourir du plus grand au plus petit | |
for ( $i = $numberOfStudents - 1; $i >= 0; $i -- ) { | |
printf( "L'étudiant %s a %d ans !", $students[ $i ]['firstname'], $students[ $i ]['age'] ); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$students = [ | |
[ | |
'firstname' => 'Alex', | |
'age' => 27, | |
], | |
[ | |
'firstname' => 'Bastien', | |
'age' => 19, | |
], | |
[ | |
'firstname' => 'Carolina', | |
'age' => 47, | |
], | |
]; | |
// pas besoin de count() avec le foreach ! | |
foreach ( $students as $student ) { | |
printf( "L'étudiant %s a %d ans !", $student['firstname'], $student['age'] ); | |
} | |
/** | |
* La clef $key contient l'index (de 0 à 2) | |
* La valeur $value contient la valeur de l'index, soit $students[0], puis $students[1] jusqu'à $students[2] | |
*/ | |
foreach ( $students as $key => $value ) { | |
printf( "L'étudiant %s a %d ans !\n", $students[ $key ]['firstname'], $students[ $key ]['age'] ); | |
printf( "L'étudiant %s a %d ans !\n", $value['firstname'], $value['age'] ); | |
} | |
// foreach peut parcourir un tableau simple ou un tableau clef/valeur ! | |
foreach ( [ 'Ben', 'Tom', 'Liz' ] as $sibling ) { | |
printf( "J'ai un frère ou une soeur qui s'appelle $sibling !\n" ); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$students = [ | |
[ | |
'firstname' => 'Alex', | |
'age' => 27, | |
], | |
[ | |
'firstname' => 'Bastien', | |
'age' => 19, | |
], | |
[ | |
'firstname' => 'Carolina', | |
'age' => 47, | |
], | |
]; | |
$numberOfStudents = count( $students ); | |
$i = 0; | |
do { | |
printf( "L'étudiant %s a %d ans !\n", $students[ $i ]['firstname'], $students[ $i ]['age'] ); | |
$i ++; | |
} while ( $i < $numberOfStudents ); | |
$i = 0; | |
while ( $i < $numberOfStudents ) { | |
printf( "L'étudiant %s a %d ans !\n", $students[ $i ]['firstname'], $students[ $i ]['age'] ); | |
$i ++; | |
} | |
// la syntaxe est différente, mais le résultat est le même ! |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Vous avez deux manières de mettre des commentaires. | |
// Celle-ci permet de mettre de petit commentaire quand c'est nécessaire. | |
/** | |
* Et voici la seconde, on l'utilise surtout pour les functions et l'utilisation d'annotations ! | |
*/ | |
echo "Utilisez-les dès que vous en avez besoin !"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Cette fonction affiche si une personne est majeure ou mineure en fonction de son âge. | |
* | |
* @param int $age l'âge de la personne a vérifier | |
*/ | |
function displayOfAge(int $age): void | |
{ | |
?> | |
<p>Avec un âge de <?php echo $age; ?>, | |
<?php echo $age >= 18 ? "vous êtes majeur !\n" : "vous êtes mineur !\n"; ?> | |
</p> | |
<?php | |
} | |
displayOfAge(18); | |
displayOfAge(17); | |
displayOfAge(24); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$lastname = "Le blanc"; | |
$age = 27; | |
//$age = 10; | |
//$age = -10; | |
/** | |
* Attention à l'ordre des conditions ! | |
* Si j'avais mis $age === 27 en dessous de $age >= 18, elle ne serait jamais passée ! | |
*/ | |
if ( $age === 27 ) { | |
echo "C'est l'âge du prof !\n"; | |
} elseif ( $age >= 18 ) { | |
echo "Je suis majeur !\n"; | |
} elseif ( $age < 0 ) { | |
echo "Je ne suis même pas né !\n"; | |
} else { | |
echo "J'ai entre 0 et 18 ans ? Eh oui Jamy !\n"; | |
} | |
if ( ! isset( $firstname ) ) { | |
echo "- Ah bon il a pas de prénom ?\n"; | |
} | |
$firstname = "Juste"; | |
if ( ! isset( $firstname ) ) { | |
echo "- Ah bon il a pas de prénom ?\n"; | |
} else { | |
echo "- Ah si, c'est $firstname $lastname !\n- Quoi ?\n"; | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$age = 27; | |
//$age = 10; | |
//$age = - 10; | |
switch ( $age ) { | |
case 27: | |
echo "C'est l'âge du prof !"; | |
break; // super important, sinon le case continue... Essaye de le supprimer ! | |
case $age > 18: | |
echo "Je suis majeur !\n"; | |
break; | |
case $age < 0: | |
echo "Je ne suis toujours pas né !"; | |
break; | |
default: // mon else | |
echo "J'ai entre 0 et 18 ans ? Eh oui Jamy !\n"; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<h1>Base de données</h1> | |
<?php | |
$dsn = 'mysql:host=mysql'; // ici, host=localhost le plus souvent. | |
$user = 'root'; | |
$password = 'root'; | |
try { | |
$dbh = new PDO($dsn, $user, $password); | |
echo "<p>Connexion ok 🎉</p>"; | |
} catch (PDOException $e) { | |
echo '<p>Connexion échouée : ' . $e->getMessage() . '</p>'; | |
} | |
$database = 'database'; | |
if (isset($dbh)) { | |
$dbh->exec("DROP DATABASE IF EXISTS $database;"); | |
echo '<p>Suppression de la base 🔴</p>'; | |
$dbh->exec("CREATE DATABASE $database;"); | |
echo '<p>Base de données créée ✅</p>'; | |
$dbh->exec("CREATE TABLE `$database`.`comment` ( | |
`id` INT NOT NULL AUTO_INCREMENT, | |
`name` VARCHAR(45) NOT NULL, | |
`email` VARCHAR(45) NOT NULL, | |
`comment` TEXT NOT NULL, | |
PRIMARY KEY (`id`)); | |
"); | |
echo '<p>Table contact créée 🗃</p>'; | |
} | |
?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="fr"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" | |
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<link rel="stylesheet" href="https://unpkg.com/mvp.css"> | |
<title>Récupérer des informations en base de données</title> | |
</head> | |
<body> | |
<main> | |
<?php | |
function getDatabaseConnection(): PDO | |
{ | |
$dsn = 'mysql:host=mysql'; | |
$user = 'root'; | |
$password = 'root'; | |
return new PDO($dsn, $user, $password); | |
} | |
$dbh = getDatabaseConnection(); | |
$statement = $dbh->prepare('SELECT * FROM `database`.`comment`;'); | |
$statement->execute(); | |
$comments = $statement->fetchAll(PDO::FETCH_ASSOC); | |
if (!empty($comments)): ?> | |
<table> | |
<thead> | |
<tr> | |
<th>Id</th> | |
<th>Nom</th> | |
<th>E-mail</th> | |
<th>Commentaire</th> | |
</tr> | |
</thead> | |
<tbody> | |
<?php foreach ($comments as $comment): ?> | |
<tr> | |
<td><code><?php echo $comment['id']; ?></code></td> | |
<td><?php echo $comment['name']; ?></td> | |
<td><a href="mailto:<?php echo $comment['email']; ?>"><?php echo $comment['email']; ?></a></td> | |
<td><?php echo $comment['comment']; ?></td> | |
</tr> | |
<?php endforeach; ?> | |
</tbody> | |
</table> | |
<?php else : ?> | |
<p>La table est vide pour le moment !</p> | |
<?php endif; ?> | |
</main> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="fr"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" | |
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<link rel="stylesheet" href="https://unpkg.com/mvp.css"> | |
<title>Formulaire POST (avec insertion en base)</title> | |
</head> | |
<body> | |
<main> | |
<h2>Poster un commentaire (en base de données)</h2> | |
<form action="/" method="post"> | |
<label for="form_name"> | |
<input id="form_name" type="text" required placeholder="Votre nom" name="name"> | |
</label> | |
<label for="form_email"> | |
<input type="email" id="form_email" required placeholder="Votre e-mail" name="email"> | |
</label> | |
<label for="form_comment"> | |
<textarea id="form_comment" name="comment" placeholder="Votre commentaire"></textarea> | |
</label> | |
<button type="submit">Poster mon commentaire</button> | |
</form> | |
<pre><code><?php print_r($_POST); ?></code></pre> | |
<?php | |
// Vérifier quye toutes les infos du formulaire sont présentes dans $_POST et qu'elles ne sont pas vide. | |
$fields = ['name', 'email', 'comment']; | |
foreach ($fields as $field) { // name, email, comment... | |
if (!array_key_exists($field, $_POST) || empty($_POST[$field])) { | |
echo "<blockquote>Tous les champs doivent être rempli !</blockquote>"; | |
exit(); | |
} | |
} | |
echo "<p>Tous les champs ont été rempli ✅</p>"; | |
// Récupération des variables du formulaire (pour plus de simplicité). | |
$name = $_POST['name']; | |
$email = $_POST['email']; | |
$comment = $_POST['comment']; | |
echo "<p>On a récupéré nos variables ✅</p>"; | |
// Connexion à la base de données | |
$dsn = 'mysql:host=mysdql'; | |
$user = 'root'; | |
$password = 'root'; | |
$dbh = new PDO($dsn, $user, $password); | |
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); | |
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); | |
echo "<p>Connexion à la base de données ✅</p>"; | |
// Insérer des données dans la base. | |
$sql = "INSERT INTO `epsi`.`comment` (name, email, comment) VALUES ('$name', '$email', '$comment');"; | |
echo "<p>Le SQL suivant a été généré ✅</p>"; | |
echo "<pre><code>$sql</code></pre>"; | |
$stmt = $dbh->prepare($sql); | |
if (!$stmt) { | |
print_r($dbh->errorInfo()); | |
} else { | |
echo "<p>SQL valide ✅</p>"; | |
} | |
$isCreated = $stmt->execute(); | |
// Afficher un message à l'utilisateur. | |
echo "<strong>"; | |
if ($isCreated) { | |
echo "Merci de votre message !"; | |
} else { | |
echo "Désolé, un problème a eu lieu :("; | |
} | |
echo "</strong>"; | |
?> | |
</main> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
error_reporting(-1); | |
ini_set('display_errors', 'On'); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Une autre manière de déclarer une fonction, on en discutera lorsque l'on parlera de "callback". | |
*/ | |
$hello = function ( string $name ): void { | |
printf( "Bonjour %s\r\n", $name ); | |
}; | |
$hello( 'Alex' ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This function is saying "hello!" to the user! | |
*/ | |
function hello( string $firstname, string $lastname ): void { | |
echo "Hello, $firstname $lastname!"; | |
} | |
hello( 'Alex', 'soyes' ); | |
hello(); // Fatal error: Uncaught ArgumentCountError: Too few arguments to function hello(), 0 passed in [...][...] on line 11 and exactly 2 expected in [...][...]. | |
/** | |
* Say "hello!" in Japanese! No last name required! | |
*/ | |
function ohayou( string $firstname, string $lastname = null ): void { | |
echo "Hello, $firstname $lastname!"; | |
} | |
ohayou( 'Alex' ); | |
/** | |
* Say "hello!" in German! No names required at all! | |
*/ | |
function gutenTag( string $firstname = "" ): void { | |
echo "Guten Tag $firstname!"; | |
} | |
gutenTag(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function countString(string $stringToCount = null): int { | |
// si je ne donne rien en paramètre ou 0. | |
if ( ! $stringToCount ) { | |
return 0; | |
} | |
return strlen( $stringToCount ); | |
} | |
echo countString( "Alex" ); | |
echo countString( "1" ); | |
echo countString( 0 ); | |
echo countString( ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class User | |
{ | |
/** @var string */ | |
private $name; | |
/** @var int */ | |
private $age; | |
/** | |
* Ne retourne rien ! | |
*/ | |
public function displayName(): void | |
{ | |
echo "Mon nom est $this->name"; | |
} | |
/** | |
* @return bool vrai ou faux suivant l'âge de la personne. | |
*/ | |
public function isOfAge(): bool | |
{ | |
return $this->age >= 18; | |
} | |
/** | |
* @return string|null retourne le nom de la personne en majuscule SI il existe. | |
*/ | |
public function getUppercaseName(): ?string | |
{ | |
if ($this->name) { | |
return strtoupper($this->name); | |
} | |
return null; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$name_value = ''; | |
$name_input = "name"; | |
/** | |
* Est-ce que la clef "name" existe dans le tableau $_GET ? | |
*/ | |
if (array_key_exists($name_input, $_GET)) { | |
$name_value = $_GET[$name_input]; | |
} | |
/** | |
* Voici un exemple d'URL généré après la validation du formulaire. | |
* | |
* http://localhost:8080/?name=Alex | |
*/ | |
?> | |
<h2>Bonjour <?php echo $name_value; ?></h2> | |
<form action="/" method="get"> | |
<label for="form_name"> | |
<!-- C'est l'attribute HTML "name" qui va se retrouver dans l'URL --> | |
<input id="form_name" type="text" required placeholder="Votre nom" name="<?php echo $name_input; ?>" | |
value="<?php echo $name_value; ?>"> | |
</label> | |
<button type="submit">Valider</button> | |
<a href="/">Vider le formulaire</a> | |
</form> | |
<pre><?php print_r($_GET); ?></pre> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="fr"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" | |
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> | |
<meta http-equiv="X-UA-Compatible" content="ie=edge"> | |
<title>Formulaire POST</title> | |
<link rel="stylesheet" href="https://unpkg.com/mvp.css"> | |
</head> | |
<body> | |
<main> | |
<h2>Poster un commentaire</h2> | |
<p>Aucun paramètre n'est présent dans l'URL, on retrouve simplement les valeurs du formulaire dans la superglobale <code>$_POST</code>.</p> | |
<form action="/" method="post"> | |
<label for="form_name"> | |
<input id="form_name" type="text" required placeholder="Votre nom" name="name"> | |
</label> | |
<label for="form_email"> | |
<input type="email" id="form_email" required placeholder="Votre e-mail" name="email"> | |
</label> | |
<label for="form_comment"> | |
<textarea id="form_comment" name="comment" placeholder="Votre commentaire"></textarea> | |
</label> | |
<button type="submit">Poster mon commentaire</button> | |
</form> | |
<pre><?php print_r($_POST); ?></pre> | |
</main> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$siblings = [ 'Ben', 'Tom', 'Liz' ]; | |
$numberOfSiblings = count( $siblings ); | |
echo "J'ai $numberOfSiblings frères et soeurs !"; | |
// Très utile pour connaître le contenu d'une variable ;-) | |
var_dump( $siblings ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class User | |
{ | |
/** @var string */ | |
private $name; | |
/** | |
* @param string $name | |
*/ | |
public function __construct(string $name) | |
{ | |
$this->name = $name; | |
} | |
/** | |
* Appelé "Getter" | |
* | |
* @return string | |
*/ | |
public function getName(): string | |
{ | |
return $this->name; | |
} | |
/** | |
* Appelé "Setter" | |
* | |
* @param string $name | |
*/ | |
public function setName(string $name): void | |
{ | |
$this->name = $name; | |
} | |
} | |
$user = new User('Alex'); | |
printf("Bonjour, je m'appelle %s", $user->getName()); | |
$user->setName('So yes'); | |
printf("Bonjour, je m'appelle %s", $user->getName()); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Le mot clé "final" empêche la classe d'étendre une autre classe. | |
* | |
* Cela peut fonctionner aussi sur les méthodes (pour empêcher un enfant de réécrire un parent". | |
* | |
* @doc https://www.php.net/manual/fr/language.oop5.final.php | |
*/ | |
final class User | |
{ | |
/** @var string */ | |
public $email; | |
/** @var string */ | |
public $password; | |
/** | |
* @param string $email | |
* @param string $password | |
*/ | |
public function __construct(string $email, string $password) | |
{ | |
$this->email = $email; | |
$this->password = $password; | |
} | |
} | |
class PasswordException extends Exception | |
{ | |
} | |
final class PasswordVerifierService | |
{ | |
private const MIN_PASSWORD_SIZE = 10; | |
private $password; | |
public function check(string $password): void | |
{ | |
$this->password = $password; | |
$this->checkForNumbers(); | |
$this->checkForLength(); | |
} | |
private function checkForNumbers(): void | |
{ | |
if (preg_match('/\\d/', $this->password) < 1) { | |
throw new PasswordException('<small>Password does not contain any numbers.</small>'); | |
} | |
} | |
private function checkForLength(): void | |
{ | |
if (strlen($this->password) < self::MIN_PASSWORD_SIZE) { | |
throw new PasswordException('<small>Password size is not matching.</small>'); | |
} | |
} | |
} | |
final class UserRegistrationService | |
{ | |
/** | |
* @var PasswordVerifierService | |
*/ | |
private $passwordVerifierService; | |
public function __construct(PasswordVerifierService $passwordVerifierService) | |
{ | |
$this->passwordVerifierService = $passwordVerifierService; | |
} | |
public function register(User $user): bool | |
{ | |
printf('<p>Registering user <a href="mailto:%1$s">%1$s</a> with password <code>%s</code></p>', $user->email, $user->password); | |
try { | |
$this->passwordVerifierService->check($user->password); | |
} catch (Exception $e) { | |
echo $e->getMessage(); | |
return false; | |
} | |
// Envoie de l'utilisateur en base de données. | |
// [...] | |
return true; // on suppose que tout s'est bien passé en base de données ;-) | |
} | |
} | |
$passwordVerifierService = new PasswordVerifierService(); | |
/** | |
* La classe "UserRegistrationService" a une dépendance, c'est le service "PasswordVerifierService" | |
* | |
* Autrement dit, elle ne peut pas fonctionner sans. | |
*/ | |
$userRegistrationService = new UserRegistrationService($passwordVerifierService); | |
$badSizedPasswordUser = new User('[email protected]', '0000'); | |
$goodUser = new User('[email protected]', 'alexandre123456789'); | |
$badUserBecauseNoNumbers = new User('[email protected]', 'alexandre-soyes'); | |
$userSuccessfullyRegistered = $userRegistrationService->register($badSizedPasswordUser); | |
if ($userSuccessfullyRegistered) { | |
printf("<strong>%s ✅</strong>", $badSizedPasswordUser->email); | |
} | |
$userSuccessfullyRegistered = $userRegistrationService->register($goodUser); | |
if ($userSuccessfullyRegistered) { | |
printf("<strong>%s ✅</strong>", $goodUser->email); | |
} | |
$userSuccessfullyRegistered = $userRegistrationService->register($badUserBecauseNoNumbers); | |
if ($userSuccessfullyRegistered) { | |
printf("<strong>%s ✅</strong>", $badUserBecauseNoNumbers->email); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
interface NameableInterface | |
{ | |
function getName(): string; | |
} | |
class Group implements NameableInterface | |
{ | |
/** @var string */ | |
private $name; | |
/** | |
* @param string $name | |
*/ | |
public function __construct(string $name) | |
{ | |
$this->name = $name; | |
} | |
/** | |
* @return string | |
*/ | |
public function getName(): string | |
{ | |
return $this->name; | |
} | |
/** | |
* @param string $name | |
*/ | |
public function setName(string $name): void | |
{ | |
$this->name = $name; | |
} | |
} | |
class User implements NameableInterface | |
{ | |
/** @var string */ | |
private $name; | |
/** | |
* @param string $name | |
*/ | |
public function __construct(string $name) | |
{ | |
$this->name = $name; | |
} | |
/** | |
* @return string | |
*/ | |
public function getName(): string | |
{ | |
return $this->name; | |
} | |
/** | |
* @param string $name | |
*/ | |
public function setName(string $name): void | |
{ | |
$this->name = $name; | |
} | |
} | |
class HelloService | |
{ | |
static function sayHello(NameableInterface $entity): void | |
{ | |
printf("Hey hey hey %s!\n", $entity->getName()); | |
} | |
} | |
$group = new Group('Teachers'); | |
$user = new User('Alex'); | |
/* | |
* Comme "Group" et "User" utilisent (implémentent) l'interface NameableInterface, on peut utiliser des fonctions communes. | |
* $group et $user sont interchangeables. | |
*/ | |
HelloService::sayHello($group); | |
HelloService::sayHello($user); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
trait NameTrait | |
{ | |
protected $name; | |
public function containsVowel(): bool | |
{ | |
return preg_match('/^[aeiou]/i', $this->name); | |
} | |
} | |
class User | |
{ | |
use NameTrait; | |
public function __construct(string $name) | |
{ | |
$this->name = $name; | |
} | |
} | |
class Group | |
{ | |
use NameTrait; | |
public function __construct(string $name) | |
{ | |
$this->name = $name; | |
} | |
} | |
$user = new User('Alex'); | |
$group = new Group('Pmlkj'); | |
if ($user->containsVowel()) { | |
echo "<p>Alex contient de voyelles !</p>"; | |
} | |
if (!$group->containsVowel()) { | |
echo "<p>Pmlkj ne contient pas de voyelles !</p>"; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
abstract class AbstractName | |
{ | |
/** @var string */ | |
private $name; | |
/** | |
* Quand on instancie les classes "User" ou "Group", c'est le constructor parent qui est appelé (en premier). | |
*/ | |
public function __construct(string $name) | |
{ | |
$this->setName($name); | |
} | |
/** | |
* Uniquement accessible dans la classe "AbstractName" | |
*/ | |
private function setName(string $name): void | |
{ | |
$name = strtoupper($name); | |
$this->name = $name; | |
} | |
/** | |
* Accessible dans la classe "Abstract" et dans les enfants qui l'implémente. | |
*/ | |
protected function getName(): string | |
{ | |
return $this->name; | |
} | |
} | |
class Group extends AbstractName | |
{ | |
/** @var array User[] */ | |
public $users = []; | |
public function displayGroupName(): void | |
{ | |
printf("<p>Nom du groupe : <code>%s</code>.</p>", $this->getName()); | |
} | |
} | |
class User extends AbstractName | |
{ | |
/** @var bool */ | |
public $isActivated = false; | |
public function displayUsernameLenght(): void | |
{ | |
printf("<p>La taille du nom %s est de %d caractères !</p>", $this->getName(), strlen($this->getName())); | |
} | |
} | |
$group = new Group('Teachers'); | |
$group->displayGroupName(); | |
$user = new User('Alex'); | |
$user->displayUsernameLenght(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
session_start(); | |
/** | |
* Si quelqu'un a posté son prénom dans un formulaire | |
* | |
* Je le sauvegarde en session | |
*/ | |
if (array_key_exists('session-firstname', $_POST)) { | |
$firstname = $_POST['session-firstname']; | |
$_SESSION['firstname'] = $firstname; | |
} | |
?> | |
<?php if (!array_key_exists('firstname', $_SESSION)): ?> | |
<form action="" method="post"> | |
<label> | |
Votre prénom | |
<input type="text" name="session-firstname" id=""> | |
</label> | |
<input type="submit" value="Envoyer"> | |
</form> | |
<?php else: ?> | |
<p>Bonjour <?php echo $_SESSION['firstname']; ?>,</p> | |
<!--On peut rafraichir la page, mais le prénom reste en "session" grace au cookie PHPSESSID--> | |
<p>Pour supprimer la session, il faut appeler <code>session_destroy();</code> !</p> | |
<?php endif; ?> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!doctype html> | |
<html lang="fr"> | |
<head> | |
<!-- Required meta tags --> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<title>Cours PHP</title> | |
</head> | |
<body> | |
<h1>Syntaxe de PHP dans du HTML</h1> | |
<?php | |
// ceci contient du code PHP | |
$name = "Alex"; | |
function count_name(): void { | |
global $name; | |
printf( "Mon prénom fait %d lettres !", strlen( $name ) ); | |
} | |
?> | |
// ceci ne contient pas de code PHP | |
$name = "Alex"; | |
<!--Et ça c'est un commentaire en HTML--> | |
<h2>On peut écrire des variables PHP dans la page</h2> | |
<?php | |
echo "<p>$name</p>"; | |
?> | |
<h3>Ou encore (plus propre)</h3> | |
<p><?php echo "<p>$name</p>"; ?></p> | |
<h2>On peut faire des conditions</h2> | |
<p> | |
<?php | |
if ( isset( $name ) ) { | |
count_name(); | |
} | |
?> | |
</p> | |
<h3>Ou mieux encore avec la "syntaxe alternative"</h3> | |
<?php if ( isset( $name ) ): ?> | |
<p><?php count_name(); ?></p> | |
<?php endif; ?> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
error_reporting(-1); | |
ini_set('display_errors', 'On'); | |
function getDatabaseConnection(): PDO | |
{ | |
$dsn = 'mysql:host=je_fais_expres_de_planter_lappli'; | |
$user = 'root'; | |
$password = 'root'; | |
// Produit une erreur : Fatal error: Uncaught PDOException: PDO::__construct(): php_network_getaddresses: getaddrinfo failed | |
return new PDO($dsn, $user, $password); | |
} | |
/** | |
* Cette ligne en dessous ne sera JAMAIS executée si une erreur de connexion à la base de produit. | |
* | |
* Commente les lignes en dessous si tu veux voir le résultat : | |
*/ | |
getDatabaseConnection(); // à commenter | |
echo "Mon code a fonctionné !"; // à commenter | |
/** | |
* La solution, "catcher" l'erreur avant qu'elle ne fasse planter la page ! | |
*/ | |
try { | |
getDatabaseConnection(); | |
} catch (Exception $e) { | |
echo "Désolé, une erreur a eu lieu ! Voici le message : <code>" . $e->getMessage() . "</code>"; | |
} | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// on crée un "objet" date | |
$date = new DateTime('1993-10-19'); | |
// on utilise la fonction "format" de l'objet "date" pour afficher la date au format français. | |
echo "Je suis né le " . $date->format( 'd/m/Y' ); | |
printf( "Je suis né le %s", $date->format( 'd/m/Y' ) ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$firstname = "Alex"; // string | |
$name = "so yes"; // string | |
$age = 27; // integer | |
$isSingle = false; // boolean | |
$isFreelance = true; // boolean | |
$siblings = [ 'Ben', 'Tom', 'Liz' ]; // array |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$GLOBALS['access'] = " (Admin)"; // Accessible from everywhere! | |
$civility = "Mrs"; // Or "Mr" if you are a men! | |
/** | |
* This function is saying "hello!" to the user! | |
*/ | |
function hello( string $firstname, string $lastname ): void { | |
echo "Hello, $civility $firstname $lastname!" . $GLOBALS['access']; | |
} | |
hello( 'Alex', 'soyes' ); // Notice: Undefined variable: civility in [...][...] on line 9 | |
/** | |
* This function is saying "hello!" to the user! | |
*/ | |
function ohayou( string $firstname, string $lastname ): void { | |
global $civility; | |
echo "Ohayou, $civility $firstname $lastname!" . $GLOBALS['access']; | |
} | |
ohayou( 'Alex', 'soyes' ); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$students = [ | |
[ | |
'firstname' => 'Alex', | |
'age' => 27, | |
], | |
[ | |
'firstname' => 'Bastien', | |
'age' => 19, | |
], | |
[ | |
'firstname' => 'Carolina', | |
'age' => 47, | |
], | |
]; | |
echo "Je m'appelle " . $students[1]['firstname'] . " et j'ai " . $students[1]['age'] . " ans.\n"; | |
// Qu'est-ce qui va s'afficher ? | |
$siblings = [ | |
'brothers' => [ 'Tom', 'Liz' ], | |
]; | |
if ( array_key_exists( 'brothers', $siblings ) ) { | |
printf( "J'ai %d frère(s) !\n", count( $siblings['brothers'] ) ); | |
} | |
if ( ! array_key_exists( 'sisters', $siblings ) ) { | |
echo "Je n'ai pas de soeurs ! (en tout cas pas encore !)\n"; | |
} | |
$siblings['sisters'] = [ 'Liz' ]; | |
if ( array_key_exists( 'sisters', $siblings ) ) { | |
echo "J'ai désormais une soeur... ! Que s'est-il passé ?\n"; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$students = [ | |
[ | |
'firstname' => 'Alex', | |
'age' => 27, | |
], | |
[ | |
'firstname' => 'Bastien', | |
'age' => 19, | |
], | |
[ | |
'firstname' => 'Carolina', | |
'age' => 47, | |
], | |
]; | |
echo "Je m'appelle " . $students[1]['firstname'] . " et j'ai " . $students[1]['age'] . ' ans.'; | |
// Qu'est-ce qui va s'afficher ? |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class Group | |
{ | |
/** @var string $name (depuis PHP8) */ | |
public string $name; | |
/** | |
* @param string $name | |
*/ | |
public function __construct(string $name) | |
{ | |
$this->name = $name; | |
} | |
} | |
class User | |
{ | |
/** @var string */ | |
public $name; | |
/** @var int */ | |
public $age; | |
/** @var Group[] */ | |
public $groups = []; // private Group[] $groups; ne fonctionne pas ! | |
/** | |
* @param string $name | |
* @param int $age | |
* @param Group[] $groups | |
*/ | |
public function __construct(string $name, int $age, array $groups) | |
{ | |
$this->name = $name; | |
$this->age = $age; | |
$this->groups = $groups; | |
} | |
} | |
$group = new Group('Admin'); | |
$user = new User('Alex', 27, [$group]); | |
printf("Le groupe de l'utilisateur est %s (merci l'autocomplétion).", $user->groups[0]->name); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Imaginons l'URL suivante : http://localhost/?firstname=alex&lastname=soyes | |
*/ | |
// attention à l'erreur : Undefined index: firstname | |
$firstname = $_GET['firstname']; | |
echo "Je suis $firstname"; | |
// ici on s'assure que la clef "firstname" est bien dans le tableau $_GET | |
if ( array_key_exists( ‘firstname’, $_GET ) ) { | |
echo "Je suis $firstname"; | |
} | |
if ( ! array_key_exists( ‘lastname’, $_GET ) ) { | |
echo "Je n'ai pas de nom de famille !"; | |
} else { | |
$lastname = $_GET['lastname']; | |
echo "Mon nom de famille est $lastname"; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$firstname = "Alex"; // string | |
$name = "so yes"; // string | |
$age = 27; // integer | |
$isSingle = false; // boolean | |
$isFreelance = true; // boolean | |
$siblings = [ 'Ben', 'Tom', 'Liz' ]; // array | |
// oups | |
echo 'Je suis $firstname $name et j\'ai $age !'; | |
// aaah :) | |
echo "Je suis $firstname $name et j'ai $age !"; | |
echo "Je suis " . $firstname . " " . $name . " et j'ai " . $age . " !"; | |
printf( "Je suis %s %s et j'ai %d ans !", $firstname, $name, $age ); | |
$age += 1; | |
echo "L'année prochaine, j'aurais $age ans !"; | |
echo "À l'heure actuelle, j'ai " . $age - 1 . " ans !"; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// On évite de donner de mauvais noms à ses variables ! | |
$a = "Alex"; | |
$b = "so yes"; | |
// Ce n'est pas parlant, qui sait ce que contient $a sans regarder ? | |
echo "Je suis $a $b"; | |
// que va afficher cette instruction ? | |
$a = "b"; | |
echo $$a; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment