Learn more about generics in PHP with examples
This article will give you an in-depth understanding of generics in PHP and introduce two generic examples. I hope it will be helpful to you!
In-depth generics
I showed a very boring generic in previous article Example, we're going to do better in this one.
$users = new Collection<User>(); $slugs = new Collection<string>();
Collections
They are probably the easiest way to explain generics, but they are also the examples everyone talks about when discussing generics. People often think of "generics" and "typed collections" as the same thing. Absolutely not the case.
So let’s look at two more examples.
This is a function called "app" - if you use a framework like Laravel, it may look familiar: This function accepts a class name, And use the dependent container to resolve an instance of that class:
function app(string $className): mixed { return Container::get($className); }
Now, you don't need to know how the container works, what's important is that this function will give you an instance of the class you requested.
So, basically, it's a generic function; a return type depends on the class name you give it. It would be cool if our IDEs and other static analyzers also understood that if I gave this function the class name "UserRepository", I wanted an instance of UserRepository returned and nothing else:
function app(string $className): mixed { /* … */ } app(UserRepository::class); // ?
Well, generics allow us to do this.
I thought now would be a good time to mention that I've been keeping a secret, like this: I mentioned in my last post that generics don't exist in PHP; well, that's not entirely true. All the static analyzers out there - tools that read code without running it, tools like your IDE - they allow doc block comments to be used for generics:
/** * @template Type * @param class-string<Type> $className * @return Type */ function app(string $className): mixed { /* … */ }
Admittedly: this is not The most perfect syntax, all static analyzers rely on a simple protocol, is that there is no official canonical syntax; however: it works. Three of the largest static analyzers in the PHP world: PhpStorm, Psalm, and PhpStan, all understand this syntax to some extent.
IDEs like PhpStorm use it to provide feedback to programmers as they write code, while tools like Psalm and PhpStan use it to bulk analyze your code base and detect potential bugs. Mainly based on type definitions.
So actually, we can build this app
function so that our tool no longer runs in the dark. Of course, PHP itself cannot guarantee that the return type is correct, because PHP will not type check the function at runtime; however, if we can trust that our static analyzer is correct, then when running it, this paragraph There is very little code - no chance of interruption.
This is the incredible power of static analysis: we can actually be sure, without running our code; that most of it will work as expected. All this is possible thanks to types - including generics.
Let's look at a more complex example:
Attributes::in(MyController::class) ->filter(RouteAttribute::class) ->newInstance() ->
Here we have a class that can "query" properties and instantiate them on the fly. I find this helper class very useful if you have used properties before knowing that their reflection API is quite verbose.
When we use the filter
method, we give it a class name for the property; then we call the newInstance
method, knowing that the result will be an instance of our filter class . Again: it would be great if our IDE understood what we are talking about.
You guessed it: Generics allow us to do this:
/** @template AttributeType */ class Attributes { /** * @template InputType * @param class-string<InputType> $className * @return self<InputType> */ public function filter(string $className): self { /* … */ } /** * @return AttributeType */ public function newInstance(): mixed { /* … */ } // … }
I hope you start to see the power of simple type information. A few years ago I needed an IDE plugin to make these insights work, now I just need to add some type information.
This latest example doesn’t just rely on generics, though, there’s another equally important part at play. Type inference: The ability of a static analyzer to "guess" - or reliably determine - types without the user specifying them. That's what's happening with the string-like annotation there. Our IDE is able to recognize the input we provide to this function as a class name and infer the type as a generic type.
So, it's all settled, right: There are generics in PHP, and all major static analyzers know how to use them. Well...there are a few caveats.
First of all, there is no official specification on what generics should look like, now each static analyzer can use their own syntax; currently, they happen to have agreed on one of them; but the future is hardly guaranteed .
Secondly: Document blocks are sub-optimal in my opinion. They feel less important in our codebase. Of course, generic annotations only provide static insight and no runtime functionality, but we've seen the power of static analysis even without runtime type checking. I think it's unfair to think of type information as "documentation comments", it doesn't convey the importance of these types in our code. That's why we got attributes in PHP8: all the functionality provided by attributes, was possible in docblock comments, but it just didn't feel good enough. The same goes for generics.
Final note: Without a proper specification, all three major static analyzers have differences between their generic implementations. PhpStorm is the most lacking one at the moment. Ideally, there would be an official specification from within PHP. But there is no official one yet.
These are the main reasons why I think it’s worth investing time in longer-lasting, more sustainable solutions. So why doesn't PHP have proper generics yet? Why do we rely on documentation chunks without clear specification?
Original address: https://stitcher.io/blog/generics-in-php-2
Translation address: https://learnku.com/php/t/ 66484
Recommended: "PHP Video Tutorial"
The above is the detailed content of Learn more about generics in PHP with examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
