ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

PHP Tutorial• 8 min read

Composer, PSR-4 Autoloading & Modern PHP 8 Features

Dependency management, match expressions, enums, and the nullsafe operator

Modern PHP 8 is a fast, typed, enterprise-grade language backed by Composer, the industry-standard package manager, and PSR standards established by the PHP-FIG community.

Modern PHP 8 Language Additions

Composer: Manages third-party packages and generates automated class autoloaders (vendor/autoload.php).

PSR-4: Specifies a standard mapping between class namespaces and directory file structures.

Match expression: A strict, expression-based upgrade to the classic switch statement that returns values directly.

Nullsafe operator (?->): Safely navigates nested object chains without cascading null checks.

PHP 8 Match Expressions and Nullsafe Operator
<?php
  // Modern PHP 8 Enum
  enum PaymentStatus: string {
    case PENDING = 'pending';
    case COMPLETED = 'completed';
    case REFUNDED = 'refunded';
    case FAILED = 'failed';
  }

  $status = PaymentStatus::COMPLETED;

  // Match expression returns a value directly
  $message = match($status) {
    PaymentStatus::PENDING   => "Payment is awaiting bank clearance.",
    PaymentStatus::COMPLETED => "Receipt sent. Thank you for your business!",
    PaymentStatus::REFUNDED  => "Funds have been returned to original card.",
    PaymentStatus::FAILED    => "Charge declined. Please update billing method.",
  };

  // Nullsafe operator: If getProfile() is null, code gracefully returns null
  $country = $user?->getProfile()?->getAddress()?->country ?? 'Unknown';

  echo "Status: " . $message . " | Region: " . $country;
?>
The nullsafe operator (?->) stops evaluation as soon as any element in the chain is null.
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which tool is the universal standard package manager for modern PHP ecosystems?