← Tilbage til koncepter

PHP Type System

Scalar types, union types, intersection types, mixed, never, void og type declarations i moderne PHP

Kategori: Fundamentals

🎯 Key Points

  • Scalar types - int, float, string, bool type hints for parametre og return types
  • Class/Interface types - Type hint med class names eller interface names
  • Union types (PHP 8.0) - Multiple mulige types med | operator (string|int)
  • Intersection types (PHP 8.1) - Object skal implementere multiple interfaces med & operator
  • nullable types - ?string syntaks for at tillade null values
  • mixed type - Accepterer alle typer (equivalent til ikke at have type hint)
  • void return type - Function returnerer intet (eller implicit null)
  • never return type (PHP 8.1) - Function exits eller thrower exception, returnerer aldrig
  • static return type - Returnerer instance af called class (LSP safe self)
  • strict_types declaration - Aktivér strict type checking mode per-file basis
  • Type coercion - Automatic conversion mellem types i coercive mode (default)
  • DNF types (PHP 8.2) - Disjunctive Normal Form for komplekse type combinations

💻 Kode Eksempel

<?php
declare(strict_types=1);

// Scalar types
function calculateArea(float $width, float $height): float {
    return $width * $height;
}

// Nullable types
function findUser(int $id): ?User {
    // Returns User or null if not found
    return null;
}

// Union types (PHP 8.0+)
function formatValue(string|int|float $value): string {
    if (is_string($value)) {
        return strtoupper($value);
    }
    return (string) $value;
}

// Multiple union types
function process(int|float $number, string|null $prefix = null): string {
    $result = (string) $number;
    return $prefix ? $prefix . $result : $result;
}

// Intersection types (PHP 8.1+)
interface Loggable {
    public function log(string $message): void;
}

interface Cacheable {
    public function cache(): void;
}

class User implements Loggable, Cacheable {
    public function log(string $message): void {
        echo "[LOG] {$message}\n";
    }
    
    public function cache(): void {
        echo "Caching user data\n";
    }
}

function processItem(Loggable&Cacheable $item): void {
    $item->log('Processing item');
    $item->cache();
}

// void return type
function logMessage(string $message): void {
    echo "[" . date('Y-m-d H:i:s') . "] {$message}\n";
    // No return statement or return; only
}

// never return type (PHP 8.1+)
function terminate(string $message): never {
    echo "Fatal error: {$message}\n";
    exit(1);
}

function throwException(): never {
    throw new RuntimeException('Always throws');
}

// static return type
class BaseModel {
    public static function create(): static {
        return new static();
    }
}

class UserModel extends BaseModel {}

// mixed type
function debugVariable(mixed $value): void {
    var_dump($value);
}

// Usage examples
echo "Area: " . calculateArea(10.5, 5.2) . "\n";

echo formatValue("hello") . "\n"; // HELLO
echo formatValue(42) . "\n";      // 42

echo process(3.14, "PI: ") . "\n"; // PI: 3.14

$user = new User();
processItem($user);

logMessage("Application started");

$model = UserModel::create(); // Returns UserModel, not BaseModel

debugVariable([1, 2, 3]);
debugVariable("test");

💼 Hvornår bruges det?

  • API request/response handling hvor DTO classes har strict types for data validation
  • Database models og entities hvor properties type-hinted til at matche database column types
  • Service layer methods hvor business logic har eksplicitte input/output type contracts
  • Value objects i domain-driven design hvor immutable objects garanterer type correctness
  • Configuration classes hvor union types tillader flexible config values (string|array|Closure)
  • Factory patterns hvor static return type sikrer subclasses returnerer korrekt type

⭐ Best Practices

  • Brug declare(strict_types=1) i alle filer - catch type errors tidligt frem for runtime failures
  • Type hint alle function parametre og return types - documentation og type safety combined
  • Prefer union types over mixed når mulige types er kendte - mixed er for bred
  • Use nullable types (?Type) eksplicit - gør det klart at null er forventet og håndteret
  • Leverage intersection types for dependencies der kræver multiple capabilities
  • Use void når function har side effects men ikke returnerer værdi - signalerer intent
  • Use never for functions der aldrig returnerer - helpful for static analysis tools
  • Avoid type coercion - strict types preventer subtle bugs fra automatic type conversions

ℹ️ Quick Info

Kategori
Fundamentals
Sværhedsgrad
Mellem til Avanceret