PHP

A popular general-purpose scripting language

PHP Overview

PHP is a popular general-purpose scripting language that is especially suited to web development. It is fast, flexible and pragmatic, powering everything from your blog to the most popular websites in the world.

Paradigm

Imperative, functional, object-oriented, procedural, reflective

Designed by

Rasmus Lerdorf

First appeared

1995

Stable release

8.2 (December 2022)

Key Features

Common Use Cases

Server-Side Web Development

Powering dynamic websites and web applications.

Content Management Systems

WordPress, Drupal, Joomla are built with PHP.

E-Commerce Platforms

Magento, WooCommerce, and others use PHP.

Web APIs

Creating RESTful APIs for mobile and web clients.

Example Code

<?php
// Modern PHP example demonstrating features

declare(strict_types=1);

// Class with type hints
class User {
    private string $name;
    private int $age;
    private array $hobbies;
    
    public function __construct(string $name, int $age, array $hobbies) {
        $this->name = $name;
        $this->age = $age;
        $this->hobbies = $hobbies;
    }
    
    public function greet(): string {
        return "Hello, my name is {$this->name}";
    }
    
    public function getHobbies(): array {
        return $this->hobbies;
    }
}

// Arrow function (PHP 7.4+)
$multiply = fn($a, $b) => $a * $b;

// Using the examples
$user = new User("Alice", 30, ["reading", "hiking"]);
echo $user->greet() . "\n";

echo "Multiply result: " . $multiply(5, 3) . "\n";

// Null coalescing operator
$username = $_GET['username'] ?? 'guest';
echo "Username: $username\n";

// JSON handling
$data = ['name' => 'Alice', 'age' => 30];
$json = json_encode($data);
echo "JSON: $json\n";

// PDO database connection
try {
    $pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
    $stmt = $pdo->query('SELECT * FROM users');
    $users = $stmt->fetchAll(PDO::FETCH_ASSOC);
    print_r($users);
} catch (PDOException $e) {
    echo "Database error: " . $e->getMessage();
}
?>

Learning Resources