How to learn method parameter type declarations
This article will introduce you to the method of learning method parameter type declaration. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
#No matter what industry you are engaged in, it is now a trend to live and learn, especially those of us who are programmers. It goes without saying that the new technology is not applicable this time. Just by studying the PHP documentation, you will find that there are many knowledge points that you do not really understand, such as the type declaration of this method parameter.
In the last article, regarding the method parameter type constraints of PHP, we said that the type constraints of method parameters are limited to classes, interfaces, arrays or callable callback functions. In fact, this is not rigorous. There is also one in PHP The definition of strict mode. If strict mode is specified, it is also effective to specify an ordinary scalar type for the method parameter type.
Definition of strict mode:
declare (strict_types = 1);
int type
function testInt(int $a) { echo $a, PHP_EOL; } testInt(1); // testInt(1.1); // Fatal error: Uncaught TypeError: Argument 1 passed to testInt() must be of the type int // testInt('52AABB'); // Fatal error: Uncaught TypeError: Argument 1 passed to testInt() must be of the type int // testInt(true); // Fatal error: Uncaught TypeError: Argument 1 passed to testInt() must be of the type int
In strict mode, it is obvious that the parameters of this method can only After receiving values of type int, other types cannot be received. Of course, no forced conversion will occur as mentioned in the previous article.
float type
function testFloat(float $a) { echo $a, PHP_EOL; } testFloat(1); testFloat(1.1); // testFloat('52AABB'); // Fatal error: Uncaught TypeError: Argument 1 passed to testInt() must be of the type int // testInt(true); // Fatal error: Uncaught TypeError: Argument 1 passed to testInt() must be of the type int
It should be noted here that PHP only has int and float, and float is a superset of int, so integers can be passed here. However, the above testInt(int $a) cannot receive float values such as 1.1. This involves the issue of up and down conversion. Converting to a superset is OK, but converting a superset to a subset is not OK.
string type
function testString(string $a) { echo $a, PHP_EOL; } // testString(1); // Fatal error: Uncaught TypeError: Argument 1 passed to testString() must be of the type string // testString(1.1); // Fatal error: Uncaught TypeError: Argument 1 passed to testString() must be of the type string testString('52AABB'); // testString(true); // Fatal error: Uncaught TypeError: Argument 1 passed to testString() must be of the type string
No need to explain too much. In non-strict mode, if we define a receiving parameter of string type, it can actually be any type. Received as string type, there is no need to talk about the type conversion here. It can be said that the effect of defining the string type in non-strict mode is the same as without any definition. But it's different in strict mode. It really can only receive string content within double quotes or single quotes.
bool type
function testBool(bool $a) { var_dump($a); } testBool(true); testBool(false); // testBool('52AABB'); // Fatal error: Uncaught TypeError: Argument 1 passed to testBool() must be of the type bool // testBool(1); // Fatal error: Uncaught TypeError: Argument 1 passed to testBool() must be of the type bool
The same goes for Boolean values. Here we can only receive the values of the true and false keywords.
Learn a new iterable type
Finally, let’s introduce a new guy. In addition to classes, arrays, and callback functions in normal mode, various scalar types in strict mode In addition to the declaration, there is also an iterable type declaration. I believe you can also see it through this word. It is an iterable type.
function testIterable(iterable $iterator) { echo gettype($iterator), ':', PHP_EOL; foreach ($iterator as $it) { echo $it, PHP_EOL; } } testIterable([1, 2, 3]); testIterable(new ArrayIterator([1, 2, 3])); // Generator对象 testIterable((function () { yield 1; yield 2; yield 3; })()); // testIterable(1); // Fatal error: Uncaught TypeError: Argument 1 passed to testIterable() must be iterable
Yes, it includes arrays, classes that implement the iterator interface, and generator-related content. That is, all the contents that can be iterated by foreach can be passed. The generator itself will be a Generator object, and in this article about learning the use of PHP generators, we have already seen the contents of this Generator object, which itself also implements the Iterator interface.
Summary
As mentioned at the beginning, it turns out that our grammar will be so different in strict mode. This time I really learned a lot. . We still have a long way to learn, and I hope you can continue to pay attention and work hard together! !
Test code:
https://github.com/zhangyue0503/dev-blog/blob/master/php/202003/source/%E5%86%8D%E6%AC%A1%E5%AD%A6%E4%B9%A0%E6%96%B9%E6%B3%95%E5%8F%82%E6%95%B0%E7%B1%BB%E5%9E%8B%E5%A3%B0%E6%98%8E.php
Recommended learning: php video tutorial
The above is the detailed content of How to learn method parameter type declarations. 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 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

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

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

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.
