PHP
01 / 06

Syntax, Types & OOP

PHP: Syntax, Types & OOP

PHP is a server-side scripting language designed for web development. PHP 8.x introduced JIT compilation, union types, fibers, readonly properties, and many modern language features that rival Python and Ruby.

Core Syntax

<?php

// Variables (dynamically typed)
$name = "Alice";
$age = 30;
$price = 9.99;
$active = true;
$nothing = null;

// String interpolation
echo "Hello, $name! You are $age years old.\n";
echo "Item costs {$item->price} USD\n";  // complex expressions need braces
echo 'No $interpolation here';            // single quotes = literal

// Heredoc / Nowdoc
$sql = <<<EOT
    SELECT *
    FROM users
    WHERE name = '$name'
EOT;

$literal = <<<'EOT'
    No $interpolation in nowdoc
EOT;

// Type juggling & casting
$num = (int) "42px";      // 42
$str = (string) 3.14;     // "3.14"
$bool = (bool) "";        // false
$arr = (array) "hello";   // ["hello"]

// Strict comparison
var_dump(0 == "a");   // true (loose) — avoid
var_dump(0 === "a");  // false (strict) — prefer

// Null coalescing
$username = $_GET['user'] ?? 'Guest';
$config['timeout'] ??= 30;  // assign if null

// Spread operator
$args = [1, 2, 3];
function sum(int ...$nums): int { return array_sum($nums); }
sum(...$args);

Arrays

// Indexed array
$fruits = ['apple', 'banana', 'cherry'];
$fruits[] = 'date';              // append
$fruits[0] = 'avocado';         // update
count($fruits);                  // 4
array_push($fruits, 'elderberry');
$last = array_pop($fruits);
array_unshift($fruits, 'first');
$first = array_shift($fruits);

// Associative array (like a map/dict)
$user = [
    'name' => 'Alice',
    'age' => 30,
    'roles' => ['admin', 'editor'],
];
$user['email'] = 'alice@example.com';
isset($user['phone']);            // false

// Array functions
sort($arr);                      // sort indexed (modifies in place)
rsort($arr);                     // reverse sort
asort($arr);                     // sort by value, preserve keys
ksort($arr);                     // sort by key
array_map(fn($x) => $x * 2, $arr);
array_filter($arr, fn($x) => $x > 0);
array_reduce($arr, fn($carry, $item) => $carry + $item, 0);
in_array('banana', $fruits);     // true/false
array_key_exists('name', $user); // true/false
array_keys($user);               // ['name', 'age', 'roles', 'email']
array_values($user);
array_merge($arr1, $arr2);
array_slice($arr, 1, 3);         // offset 1, length 3
array_splice($arr, 1, 2, ['x']); // remove 2, insert 'x' at pos 1
array_unique($arr);              // remove duplicates
array_flip($arr);                // swap keys and values
array_column($users, 'email');   // extract column from 2D array

OOP

<?php

// Modern PHP class
class User
{
    public function __construct(
        private readonly int $id,
        private string $name,
        private string $email,
        private array $roles = [],
    ) {}

    public function getName(): string { return $this->name; }

    public function rename(string $name): void
    {
        if (strlen($name) < 2) {
            throw new \InvalidArgumentException("Name too short");
        }
        $this->name = $name;
    }

    public function hasRole(string $role): bool
    {
        return in_array($role, $this->roles, strict: true);
    }

    public function withRole(string $role): static  // covariant return
    {
        $clone = clone $this;
        $clone->roles[] = $role;
        return $clone;
    }

    public function toArray(): array
    {
        return ['id' => $this->id, 'name' => $this->name, 'email' => $this->email];
    }

    // Magic methods
    public function __toString(): string { return $this->name; }
    public function __get(string $prop): mixed { return $this->$prop ?? null; }
}

// Interface + abstract class
interface Notifiable {
    public function notify(string $message): void;
}

abstract class BaseModel {
    abstract public function validate(): bool;

    public function save(): void {
        if ($this->validate()) {
            // save to DB
        }
    }
}

// Traits (mixins)
trait Timestamps {
    private \DateTimeImmutable $createdAt;

    public function initTimestamps(): void {
        $this->createdAt = new \DateTimeImmutable();
    }

    public function getCreatedAt(): \DateTimeImmutable {
        return $this->createdAt;
    }
}

// Enums (PHP 8.1+)
enum Status: string {
    case Active = 'active';
    case Inactive = 'inactive';
    case Pending = 'pending';

    public function label(): string {
        return match($this) {
            Status::Active => 'Active',
            Status::Inactive => 'Inactive',
            Status::Pending => 'Awaiting Review',
        };
    }
}

$status = Status::Active;
$status->value;          // 'active'
$status->label();        // 'Active'
Status::from('pending'); // Status::Pending

Keep your own version of these notes — editable, searchable, and organised by your stack.

Start free