The Enduring Power of PHP
PHP powers roughly 75% of websites with known server-side programming languages, including WordPress, Wikipedia, and thousands of enterprise platforms. Far from the legacy PHP 4 of the early 2000s, modern PHP 8.x is a mature, strictly typed language equipped with JIT compilation, constructor property promotion, and enums.
1. Syntax & Strict Typing
Always enforce strict scalar types at the top of your PHP files:
<?php
declare(strict_types=1);
function formatQuizScore(string $candidateName, int $score, int $total): string {
$percentage = round(($score / $total) * 100);
return sprintf('%s scored %d%% (%d/%d)', $candidateName, $percentage, $score, $total);
}
echo formatQuizScore('Sarah', 18, 20); // Sarah scored 90% (18/20)
2. Associative Arrays & Data Handling
PHP arrays can function as indexed lists, associative maps, or nested multi-dimensional structures:
$quizAttempt = [
'user_id' => 1042,
'technology' => 'PHP',
'score' => 85,
'passed' => true,
'answered_questions' => [1, 2, 3, 4, 5]
];
// Check key existence and print
if ($quizAttempt['passed']) {
echo "Congratulations! You earned a {$quizAttempt['technology']} certificate.";
}
3. Object-Oriented PHP with Constructor Promotion
PHP 8 introduced Constructor Property Promotion, dramatically reducing boilerplate:
<?php
declare(strict_types=1);
class Certificate {
public function __construct(
public readonly string $id,
public readonly string $candidateName,
public readonly string $technology,
public readonly int $percentage,
public readonly DateTimeImmutable $issuedAt = new DateTimeImmutable()
) {}
public function isHonors(): bool {
return $this->percentage >= 90;
}
}
$cert = new Certificate('CERT_9941', 'Dania', 'PHP 8', 92);
echo $cert->isHonors() ? 'Honors Credential' : 'Passing Credential';
4. Secure Database Access with PDO
Never concatenate raw user input into SQL queries. Use PHP Data Objects (PDO) with prepared statements:
<?php
$dsn = 'mysql:host=localhost;dbname=quizapp;charset=utf8mb4';
$pdo = new PDO($dsn, 'db_user', 'secure_password', [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
]);
// Parameterized Query: Immune to SQL Injection
$stmt = $pdo->prepare('SELECT id, name, question_count FROM categories WHERE is_enabled = :enabled');
$stmt->execute(['enabled' => 1]);
$activeCategories = $stmt->fetchAll();
Frequently Asked Questions
What are PHP superglobals?
Superglobals are built-in arrays accessible everywhere in your code without global keywords, such as $_POST, $_GET, $_SESSION, and $_SERVER.
Why should I disable PDO emulated prepares?
Setting PDO::ATTR_EMULATE_PREPARES => false ensures that parameter values and SQL query templates are transmitted to the database engine separately, preventing SQL injection bypasses.
Explore More
- Take the PHP Quizzes Track on Hangbug.
- Test your backend knowledge in the Laravel Basics Guide.