PHP 8.4 New Features: Fibers, Property Hooks, and Modern PHP Development

PHP 8.4 has solidified PHP as a modern, performant language. Let us explore the latest features that make PHP development better than ever.

Property Hooks

Property hooks eliminate the need for boilerplate getters and setters:

class User {
    public string $name {
        set(string $value) => $this->name = trim($value);
        get => ucfirst($this->name);
    }
    
    public string $email {
        set(string $value) {
            if (!filter_var($value, FILTER_VALIDATE_EMAIL)) {
                throw new InvalidArgumentException("Invalid email");
            }
            $this->email = strtolower($value);
        }
    }
}

Asymmetric Visibility

class Product {
    public private(set) string $name;
    public protected(set) float $price;
    
    public function __construct(string $name, float $price) {
        $this->name = $name;
        $this->price = $price;
    }
}

Enhanced Enums

enum Status: string {
    case Active = "active";
    case Inactive = "inactive";
    case Pending = "pending";
    
    public function label(): string {
        return match($this) {
            self::Active => "Active User",
            self::Inactive => "Inactive User",
            self::Pending => "Pending Approval",
        };
    }
    
    public function canLogin(): bool {
        return $this === self::Active;
    }
}

Fibers for Async Operations

$fiber = new Fiber(function (): void {
    $response = fetchFromAPI(); // Suspends here
    Fiber::suspend($response);
    
    $processed = processData($response);
    Fiber::suspend($processed);
});

$apiData = $fiber->start();
$result = $fiber->resume();

Match Expressions

$result = match(true) {
    $age < 13 => "child",
    $age < 18 => "teenager",
    $age < 65 => "adult",
    default => "senior"
};

Readonly Classes

readonly class Config {
    public function __construct(
        public string $dbHost,
        public int $dbPort,
        public string $dbName,
    ) {}
}

Modern PHP Best Practices

  • Use strict types: declare(strict_types=1);
  • Leverage union types and intersection types
  • Use named arguments for clarity
  • Adopt PSR-12 coding standard
  • Use Composer for dependency management
  • Write tests with PHPUnit or Pest

Conclusion

PHP 8.4 is a joy to work with. Property hooks, asymmetric visibility, and improved enums make the language more expressive and safer. If you have not upgraded yet, now is the time.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Privacy Policy · Contact · Sitemap

© 7Tech – Programming and Tech Tutorials