Learn more about generics in PHP with examples

青灯夜游
Release: 2023-04-10 22:50:01
forward
5376 people have browsed it

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!

Learn more about generics in PHP with examples

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>();
Copy after login

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.

Learn more about generics in PHP with 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);
}
Copy after login

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); // ?
Copy after login

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
{ /* … */ }
Copy after login

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()
    ->
Copy after login

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
    { /* … */ }

    // …
}
Copy after login

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!

Related labels:
source:learnku.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!