Home > Article > Backend Development > The new features of PHP8, the constructor attribute, are greatly enhanced!
December 3. In addition to a large number of bug fixes and small improvements, developers around the world will also get some new interesting features. The list isn't over yet, but we can take a look at the new features we're looking forward to. I’m going to prepare a series of short articles, each one will be focused on, so let’s get started!
In the first article, I introduce to youConstructor attribute promotion. PHP8 will introduce a concept that is famous in languages like Hack, Korlin or TypesScript. How does it work and in what situations can it be used? Let's look at the following example:
Pretty simple numeric object, isn't it? We deal with this type almost every day. Whenever we need to pass a value from a constructor parameter to a property in the class, we need to write the entire block of template code as shown in the figure, which is indeed a bit annoying. The constructor attribute promotion function will solve this problem for us, and can make similar code writing shorter and simpler. Let's take a look at how to use it: We can simply add an access modifier before the type declaration of the constructor parameter, and then the parameter will be automatically assigned to the Class attribute with the same name. We can understand that in the constructor, parameters with access modifiers will be promoted and become class attributes with the same name. You can mix property promotions with regular property declarations. As shown in the following example: The above example code is equivalent to the code in the following example: Constructor attribute Promotion (Constructor Property Promotion) can only be used in regular classes andtraits reference classes. It cannot be used in interfaces and abstract classes (although we can declare constructors in these classes).
Value Objects (VO) or Data Transfer Objects (DTO), Constructor Property Promotion will be greatly Simplify and shorten your code. Similar feature requests were discussed several times, but only the implementation written by Nikita Popov received enough favorable reviews that it will be merged into the new PHP version. You can read more about it in this RFC.
In the next part of the "In-depth PHP8" series, we will discuss the implementation of union types. Stay tuned!here to view.
Original address: https://dev.to/avantar/pe-into-php8-pa...Translation address: https://learnku. com/laravel/t/47600
The above is the detailed content of The new features of PHP8, the constructor attribute, are greatly enhanced!. For more information, please follow other related articles on the PHP Chinese website!