New Features In PHP 8 2021

New Features In PHP 8 2021

·

2 min read

What's New In PHP 8?

  • Constructor Property Promotion
  • Validation for Abstract Trait Methods
  • Incompatible Method Signatures
  • Arrays Starting With a Negative Index
  • Union Types 2.0
  • Stricter Type Checks for Arithmetic/Bitwise Operators
  • Match Expression v2
  • Saner Numeric Strings
  • Saner String to Number Comparisons
  • Nullsafe Operator
  • Named Arguments
  • Attributes v2
  • Allows class syntax on objects
  • Trailing Comma in Parameter List
  • Consistent Type Errors for Internal Functions
  • Throw Expression
  • Weak Maps

New Features In PHP 8

1. Constructor Property Promotion in PHP 8

Constructor Property is only related to promoted parameters. And all parameters are prefixed with the public, protect, and private keywords. In PHP 8 most of the properties are repeated but we can also use them with an object. Those are the best new features in PHP 8.

Constructor Property helps to reduce the common code while you are creating an object. It allows combining fields, the definition of the constructor, and variable assignment all in one syntax into the constructor. Now, let's see the example.

1.png

2. Validation for Abstract Trait Methods in PHP 8

Trait methods define as a mechanism in PHP and its reuse in inheritance language. But the most used method is the declared method that can use in multiple classes. The trait can also contain abstract methods, which are used to specify the requirements the trait has on the user class. Here, I've listed one of the best new features in PHP 8. Let's see the example.

2.png

3. Incompatible Method Signatures in PHP 8

In PHP, inheritance error occurs through incompatible method signature. If the class implementing an interface then it threw the fatal error. According to Object Interface Documentation(OID), the class implementing that must use method signature which compatible withLiskov Substitution Principle, if do not this then fatal error will occur. That is a useful new feature in PHP 8.Example of Incompatible Metod Signature:

3.png

4. Arrays Starting With a Negative Index in PHP 8

An array is just one type of ordered map. using an array you can use positive or negative integer, and string as key values. I think that's one of the best new features in PHP 8. A negative key is to have a special meaning in this language, like any other value the can be the key of the associate array. Let's see the Example:

4.png

Get All the examples from here