Modern PHP 8 Syntax & Type Declarations
Explore PHP 8.x features including strict typing, match expressions, nullsafe operators, and constructor property promotion.
The Renaissance of Modern PHP
PHP 8 powers a vast portion of the global web. Modern PHP has evolved with a high-performance JIT compiler, strict type declarations, and expressive object-oriented paradigms.
💡 Strict Types in PHP
Declare declare(strict_types=1); at the very top of your PHP scripts to enforce compiler-level argument and return type verification, preventing accidental coercion.
<?php
declare(strict_types=1);
class BookLesson {
public function __construct(
public readonly string $title,
public readonly int $readTimeMinutes,
public bool $isCompleted = false
) {}
public function markCompleted(): void {
$this->isCompleted = true;
}
}
$lesson = new BookLesson('PHP 8 Architecture', 10);
$lesson->markCompleted();
echo "Lesson '{$lesson->title}' status: " . ($lesson->isCompleted ? 'Complete' : 'Pending');
?>
Console Output
Press "Run Code" to execute in virtual runtime.
PDO Prepared Statements & SQL Injection Defense
Eliminate SQL injection vulnerabilities by connecting to MySQL/MariaDB using PHP Data Objects (PDO) and parameterized queries.
The Gold Standard of Database Interaction
Concatenating raw user variables into SQL query strings is the number one cause of database breaches. Prepared statements separate SQL instructions from query data, rendering SQL injection mathematically impossible.
<?php
// Secure PDO Connection with Prepared Statement
$dsn = 'mysql:host=localhost;dbname=hk1_learning;charset=utf8mb4';
$pdo = new PDO($dsn, 'db_user', 'super_secret_password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
]);
$stmt = $pdo->prepare('SELECT id, title, level FROM courses WHERE category = :cat');
$stmt->execute(['cat' => 'Web Development']);
$courses = $stmt->fetchAll();
foreach ($courses as $c) {
echo htmlspecialchars($c['title']) . PHP_EOL;
}
?>
Console Output
Press "Run Code" to execute in virtual runtime.
PHP Server Architecture Quiz
Test your understanding of PDO statements, superglobals, and PHP 8 type mechanics.
PHP Server Capstone Projects
Build an authenticated member registration system and a lightweight REST API.
Implement user registration, login, and session persistence using password_hash(PASSWORD_BCRYPT) and CSRF token verification.
// Secure password hashing demonstration
$hashed = password_hash($rawPassword, PASSWORD_DEFAULT);
if (password_verify($inputPassword, $hashed)) {
session_regenerate_id(true);
$_SESSION['authenticated'] = true;
}
Develop a RESTful microservice in PHP that responds with JSON payloads, sets appropriate HTTP status codes, and enforces API key authentication.
header('Content-Type: application/json');
echo json_encode(['status' => 'success', 'data' => []]);