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!

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP is not dead. 1) The PHP community actively solves performance and security issues, and PHP7.x improves performance. 2) PHP is suitable for modern web development and is widely used in large websites. 3) PHP is easy to learn and the server performs well, but the type system is not as strict as static languages. 4) PHP is still important in the fields of content management and e-commerce, and the ecosystem continues to evolve. 5) Optimize performance through OPcache and APC, and use OOP and design patterns to improve code quality.

PHP and Python have their own advantages and disadvantages, and the choice depends on the project requirements. 1) PHP is suitable for web development, easy to learn, rich community resources, but the syntax is not modern enough, and performance and security need to be paid attention to. 2) Python is suitable for data science and machine learning, with concise syntax and easy to learn, but there are bottlenecks in execution speed and memory management.

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Using preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.


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

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Zend Studio 13.0.1
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor