PHP 8 - new features: part 2

Let’s go ahead and check out fresh new expressions and return types in PHP 8...


Match expression

Unlike the “switch” expression in php, the match expression doesn’t require the break statement. It works exactly like a switch expresion. It uses strict comaprisons and doesn’t support type coersion.

Example:

$result = match($input) {
0 => "hello",
'1', '2', '3' => "world",
};

New “static” return type

Now, static can be used as a return type! This feature will be very useful to the developers due to PHP’s dynamically typed nature.

Example:

class Foo {
public function test(): static
{
return new static();
}
}

New mixed type

The mixed type can be used when we are experiencing one of the following things:

  1. A function returns nothing or null
  2. We're expecting one of several types
  3. We're expecting a type that can't be type hinted in PHP

“mixed” type can mean any one of the following things:

  1. array
  2. bool
  3. callable
  4. int
  5. float
  6. null
  7. object
  8. resource
  9. string

Note:mixed type can also be used as a parameter or property type. Also note that since mixed already includes null, it's not allowed to make it nullable.

Throw expression

“throw” is no more a statement, but an expression now, which enables us to throw exceptions in many new places.

Example:

$triggerError = fn () => throw new MyError();

$foo = $bar['offset'] ?? throw new OffsetDoesNotExist('offset');

Did you like our works?

We are known for Website Development and Website Designing, along with Android iOS application development in Mumbai, India. Please write us what you think, we would like to hear it from you

1