Let's talk about the basic knowledge of generics in PHP
This article will take you to talk about generics in PHP. First, let’s understand the basic knowledge of PHP generics. In the following articles, we will take you to have an in-depth understanding of generics. I hope it will be helpful to you!
Generics in PHP. I knew this was what I wanted. I know a lot of developers want this 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 why they have this type.
I will be doing a series of articles on this blog about generics and PHP. Let's start at the beginning and soon we will get to more complex topics. We'll discuss what generics are, why PHP doesn't support them, and what might happen in the future.
let's start.
Every programming language has some type of system. Some languages are very strict in their implementation, while other languages - and PHP falls into this category - are much looser
Now, there are many reasons to use a type system. The most obvious is type verification.
Suppose we have a function that accepts two numbers, two integers; and does some math on them:
function add($a, $b) { return $a + $b; }
PHP allows you to pass any type of data to the function, numbers , string, and Boolean values do not matter. PHP will do its best to transform variables when it makes sense, such as adding them together.
add('1', '2');
But these conversions - type juggling - often lead to unexpected results, or rather: errors and crashes.
add([], true); // ?
Now, we can manually write code to check that our mathematical addition operation 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 hints – this is the built-in shorthand for what we do 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 type hints because they know they should only pass integers to this function - it's them after all written.
However, this reasoning quickly breaks down: you're often not the only one working in that codebase, and you're using code you didn't write yourself - think of how much you introduced with Composer Bag. So while this isolated example may not seem like a big deal, type checking does come in handy once your code starts growing.
Beyond that, adding type hints not only prevents invalid states, 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 a function's functionality is already encapsulated by its type definition.
IDEs make heavy use of this principle: they can tell the programmer what type of value input a function expects, or what fields and methods are available on an object - because it belongs to a class. IDEs make us write code more efficiently, in large part because they can statically analyze type hints in our code base.
Remember this word: static analysis - This will be very important later in this series. This means that a program, IDE, or other type of "static analyzer" can look at our code and tell us whether it will work 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're doing wrong - which will cause the program to crash at runtime; but our IDE can tell us without actually running the code. .
On the other hand, the type system also has its limitations. A common example is "item 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 methods to handle any type of input: looping, filtering, mapping, etc.; the collection implementation should not care whether it handles strings or integers .
But let’s look at it from an outsider’s perspective. What happens if we want to make sure that one collection only contains strings and another collection only contains "user" objects. The collection itself doesn't care when looping through its items
, but we do. We want to know if the item in the loop is a user or a string - that's completely different. But without the correct type information, our IDE will run in unknown circumstances.
$users = new Collection(); // … foreach ($users as $user) { $user-> // ? }
Now we can create separate implementations for each collection: one that only works with strings, and another that only works with User
objects:
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? Maybe 10 or 20. Managing these codes will become very difficult.
This is where generics come in.
It needs to be clarified: PHP does not have generics. It’s a bold statement that takes quite a few detours, which we’ll discuss later in this series. But now I can say that what I'm going to show you doesn't exist in PHP. But it exists in other programming languages.
Many programming languages allow developers to define "generics" on collection classes, rather than implementing separate implementations for each possible type:
class Collection<Type> extends ArrayObject { public function offsetGet(mixed $key): Type { /* … */ } // … }
基本上我们说的是集合类的实现适用于任何类型的输入,但是当我们创建集合的实例时,我们应该指定一个类型。它是一个泛型实现,需要根据程序员的需求来特定:
$users = new Collection<User>(); $slugs = new Collection<string>();
添加类型似乎是一件小事。但这种类型本身就开启了一个充满可能性的世界。 我们的 IDE 现在知道了集合中的数据类型,它可以告诉我们是否添加了错误类型的项;它可以告诉我们在迭代集合时可以对项执行什么操作;它可以告诉我们是否将集合传递给知道如何处理这些特定项的函数。
虽然我们可以通过手动为我们需要的每种类型实现一个集合,在技术上实现同样的效果;对于编写和维护代码的开发人员来说,通用实现将是一项重大改进。
那么,我们为什么不在 PHP 中使用泛型呢?除了无聊的收藏,我们还能用它们做什么?我们能为他们增加支持吗?我们将在这个系列中回答所有这些问题。首先需要澄清的是:我在本系列文章中的目标是教你关于泛型的知识,但同样重要的是,我想让大家意识到我们是如何误解 PHP 的。我想改变这种状况。
英文原文地址:https://stitcher.io/blog/generics-in-php-1
推荐:《PHP视频教程》
The above is the detailed content of Let's talk about the basic knowledge of generics in PHP. 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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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 and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
