minte9
LearnRemember / PHP





Union Types

A collection of different datatypes in the same memory location.
 
declare(strict_types=1);

/**
 * Union Types
 * 
 * Prior to PHP 8.0 you could only declare a single type for properties, parameters, 
 * and return types.
 * 
 * Starting with PHP 8.2 you can use them even in class property declaration
 * 
 * To separate each datatype use pipe |
 * The ?string is equivalent with string|null
 */

class MyClass 
{
    private int|float $i = 10; // Look Here
    
    public function set(int|float $n, ?string $name): void
    {
        $this->i +=  $n;
    }

    public function get(): int|float
    {
        return $this->i;
    }
}

$a = new MyClass();
$b = new MyClass();

$a->set(10, "one");
$b->set(5.5, NULL); 

echo $a->get(); // 20
echo $b->get(); // 5.5

Match

Match expression improves the switch syntax in multiple ways.
 
declare(strict_types=1);

/**
 * Match expression
 * 
 * Match syntax improves the switch syntax in multiple ways:
 * returns value; multiple matching conditions allowed
 * implicit break; strict matching (value and type)
 */

class B 
{
    public String $request_method = 'GET';

    public function __construct(String $request_method) 
    {
        $result = match($request_method) { // Look Here
            
            'POST' => $this->handle_post(),
            'GET', 'HEAD' => $this->handle_get(),
            default => throw new \Exception('Unsupported'),
        };

        echo $result;
    }

    private function handle_post(): String
    {
        return 'This is POST';
    }

    private function handle_get(): String
    {
        return 'This is GET';
    }
}

try {
    new B('POST'); // This is POST
    new B('GET');  // This is GET
    new B('HEAD'); // This is GET
    new B('HTTP'); // Unsupported
} catch(Exception $e) {
    echo $e->getMessage(); 
}



  Last update: 12 days ago


Questions and answers:




To separate diffent types use:

  • a) comma
  • b) pipe

Match expression improves:

  • a) switch syntax
  • b) regex syntax


References and applications: