Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basics of generics in PHP

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

What are the knowledge points of this article "what are the basics of generics in PHP?" most people do not understand, so the editor summarizes the following contents, detailed contents, clear steps, and has a certain reference value. I hope you can get something after reading this article. Let's take a look at this "what are the basics of generics in PHP" article.

Generics in PHP. I know that's what I want. I know a lot of developers want to use this type. On the other hand, there may be a large group of PHP programmers who don't know what generics are or think why they have this type.

I will do a series of articles on generics and PHP on this blog. Let's start from the beginning, and soon we'll find a more complicated topic. We'll discuss what generics are, why PHP doesn't support them, and what might happen in the future.

Let's get started.

Every programming language has some kind of system. Some languages are very strict in implementation, while others-- PHP falls into this category-- are much more relaxed.

Today, there are many reasons for using a type system. The most obvious is type validation.

Suppose we have a function that accepts two numbers and two integers, and performs some mathematical operations on them:

Function add ($a, $b) {return $a + $b;}

PHP allows you to pass any type of data to this function, regardless of numbers, strings, or Boolean values. PHP will do its best to convert variables when meaningful, such as adding them together.

Add ('1x,'2')

But these conversions-- type juggling-- often lead to unexpected results, or: errors and crashes.

Add ([], true); / /?

Now, we can manually write code to check our mathematical addition, which will be used for any given input

Function add ($a, $b) {if (! is_int ($a) | |! is_int ($b)) {return null;} return $a + $b;}

Alternatively, we can use the PHPS built-in type hint-this is our built-in shorthand for performing operations manually:

Function add (int $a, int $b): int {return $a + $b;}

Many developers in the PHP community say they don't really care about these types of hints because they know they should only pass integers to this function-after all, they wrote it themselves.

However, this reasoning will soon unravel: you are not usually the only one working in this code base, and you are still using code that you did not write yourself-think about how many packages you have introduced with Composer. So while this isolated example doesn't seem like a big deal, type checking does come in handy once your code starts to grow.

In addition, adding type hints not only prevents invalid status, but also clarifies what type of value input we programmers need. Defining a type usually eliminates the need to read external documentation, because most of the functionality of a function is already encapsulated by its type definition.

IDE makes extensive use of this principle: they can tell programmers what type of value input a function expects, or which fields and methods are available on an object-- because it belongs to a class. IDE makes our code more efficient, in large part because they can statically analyze type hints in our code base.

Remember the word: static analysis-this will be very important later in this series. This means that programs, IDE, or other types of "static parsers" can look at our code and tell us if it works without running it-- at least to some extent. If we pass a string to our function that only accepts integers, our IDE will tell us what we did wrong-which can cause the program to crash at run time; but our IDE can tell us without actually running the code.

On the other hand, the type system has its limitations. A common example is the "project list":

Class Collection extends ArrayObject {public function offsetGet (mixed $key): mixed {/ * … * /} public function filter (Closure $fn): self {/ * * /} public function map (Closure $fn): self {/ * * /}}

A collection has many ways to handle any type of input: looping, filtering, mapping, and so on; the collection implementation should not care whether it handles strings or integers.

But let's look at it from an outsider's point of view. What happens if we want to make sure that one collection contains only strings and another collection contains only "user" objects. The collection itself does not care when looping its items, but we do. We want to know whether the item in the loop is a user or a string-- this is completely different. But without the correct type information, our IDE will run in an unknown situation.

$users = new Collection (); / / … Foreach ($users as $user) {$user- > / /?}

Now we can create a separate implementation for each collection: one for strings only and the other for User objects only:

Class StringCollection extends Collection {public function offsetGet (mixed $key): string {/ * … Class UserCollection extends Collection {public function offsetGet (mixed $key): User {/ * … * /}}

But what if we need a third implementation? The fourth one? Maybe 10 or 20. It will be very difficult to manage this code.

This is the opportunity for generics to show their talents.

What needs to be clarified is that PHP does not have generics. This is a bold statement that has taken a lot of detours, which we will discuss later in this series. But now I can say that what I'm going to show is not available in PHP. But it exists in other programming languages.

Many programming languages allow developers to define "generics" on collection classes, rather than implementing them separately for each possible type:

Class Collection extends ArrayObject {public function offsetGet (mixed $key): Type {/ * … * /} / /... }

Basically what we're saying is that the implementation of the collection class is suitable for any type of input, but when we create an instance of the collection, we should specify a type. It is a generic implementation that needs to be specified according to the needs of the programmer:

$users = new Collection (); $slugs = new Collection ()

Adding a type seems like a small matter. But this type itself opens up a world full of possibilities. Our IDE now knows the data types in the collection, which can tell us whether items of the wrong type have been added; it can tell us what to do with items when iterating over the collection; and it can tell us whether to pass the collection to functions that know how to handle these specific items.

The above is about the content of this article on "what are the basics of generics in PHP?" I believe we all have a certain understanding. I hope the content shared by the editor will be helpful to you. If you want to know more about the relevant knowledge, please follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report