Skip to content

Latest commit

 

History

History
272 lines (219 loc) · 5.46 KB

File metadata and controls

272 lines (219 loc) · 5.46 KB

Modern PHP Features (PHP 7.4 - 8.3)

The Problem

Writing PHP 5.6 style code in PHP 8+:

  • Misses out on safety - No type checking
  • More verbose - More code to write
  • Less expressive - Harder to read
  • Behind the times - Not using modern tools

Modern PHP Features

PHP 7.4+

Typed Properties

// Old
private $name;

// New
private string $name;

Arrow Functions

// Old
array_map( function( $x) { return $x * 2; }, $array);

// New
array_map( fn( $x) => $x * 2, $array);

Null Coalescing Assignment

// Old
if ( !isset( $data['key'])) {
    $data['key'] = 'default';
}

// New
$data['key'] ??= 'default';

PHP 8.0+

Named Arguments

// Old - what does each value mean?
wp_remote_get( $url, array( 30, 5, true));

// New - crystal clear!
wp_remote_get(
    $url,
    timeout: 30,
    redirection: 5,
    sslverify: true
);

Constructor Property Promotion

// Old
class User {
    private string $name;
    
    public function __construct( string $name) {
        $this->name = $name;
    }
}

// New - one line!
class User {
    public function __construct(
        private string $name
    ) {}
}

Union Types

// Old - no type safety
function process( $input) { }

// New - type-safe!
function process( int|string $input): bool { }

Match Expression

// Old - verbose switch
switch ( $status) {
    case 'pending': return 'Pending'; break;
    case 'approved': return 'Approved'; break;
    default: return 'Unknown';
}

// New - expression!
return match( $status ) {
    'pending' => 'Pending',
    'approved' => 'Approved',
    default => 'Unknown',
};

Nullsafe Operator

// Old - manual null checks
$country = null;
if ( $user !== null) {
    if ( $user->address !== null) {
        $country = $user->address->country;
    }
}

// New - chain safely!
$country = $user?->address?->country;

PHP 8.1+

Enums

// Old - constants
class Status {
    const PENDING = 'pending';
    const APPROVED = 'approved';
}

// New - type-safe enums!
enum Status: string {
    case PENDING = 'pending';
    case APPROVED = 'approved';
    
    public function label(): string {
        return match( $this ) {
            self::PENDING => 'Pending Approval',
            self::APPROVED => 'Approved',
        };
    }
}

// Usage
function update( Status $status ): void {
    // Type-safe! Can't pass invalid value
}

update( Status::APPROVED );

Readonly Properties

// Old - manually enforce immutability
class Config {
    private string $apiKey;
    
    public function __construct( string $apiKey) {
        $this->apiKey = $apiKey;
    }
    
    public function getApiKey(): string {
        return $this->apiKey;
    }
}

// New - readonly keyword!
class Config {
    public function __construct(
        public readonly string $apiKey
    ) {}
    
    // Cannot be modified after construction!
}

First-class Callables

// Old
array_map( fn( $x) => strtoupper( $x), $names);

// New
array_map( strtoupper( ... ), $names );

PHP 8.2+

Readonly Classes

// All properties automatically readonly
readonly class Point {
    public function __construct(
        public float $x,
        public float $y
    ) {}
}

Quick Reference

Feature PHP Version Example
Type Hints 7.0+ function foo(string $x): int
Null Coalescing 7.0+ $x = $y ?? 'default'
Short Arrays 5.4+ [1, 2, 3] instead of array(1, 2, 3)
Typed Properties 7.4+ private string $name;
Arrow Functions 7.4+ fn($x) => $x * 2
Named Arguments 8.0+ foo(name: 'John')
Constructor Promotion 8.0+ public function __construct(private string $name) {}
Union Types 8.0+ int|string|null
Match 8.0+ match($x) { 1 => 'one', default => 'other' }
Nullsafe Operator 8.0+ $user?->address?->country
Enums 8.1+ enum Status { case ACTIVE; }
Readonly 8.1+ readonly class Foo

Benefits

Type Safety - Catch errors at compile time
Less Code - Property promotion, arrow functions
More Expressive - Match, enums, named arguments
Safer - Readonly, nullsafe, strict types
Modern - Using latest features

Key Takeaways

Use type declarations everywhere
Use named arguments for clarity
Use match instead of switch
Use enums for constants
Use readonly for immutability
Use nullsafe operator for chaining
Use arrow functions for callbacks
Use constructor promotion in classes

❌ Don't write PHP 5.6 style code
❌ Don't skip type declarations
❌ Don't use old array() syntax
❌ Don't avoid modern features

The Bottom Line

Modern PHP is powerful, safe, and expressive.

// Old way (PHP 5.6)
class UserService {
    private $repo;
    private $validator;
    
    public function __construct( $repo, $validator) {
        $this->repo = $repo;
        $this->validator = $validator;
    }
    
    public function create( $data) {
        // No types, verbose, unsafe
    }
}

// Modern way (PHP 8.1+)
class UserService {
    public function __construct(
        private readonly UserRepository $repo,
        private readonly UserValidator $validator
    ) {}
    
    public function create( array $data ): int|WP_Error {
        // Typed, concise, safe!
    }
}

Upgrade to PHP 8+ and use modern features!