search
HomeBackend DevelopmentPHP ProblemHow 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.

How to learn method parameter type declarations

#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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
ACID vs BASE Database: Differences and when to use each.ACID vs BASE Database: Differences and when to use each.Mar 26, 2025 pm 04:19 PM

The article compares ACID and BASE database models, detailing their characteristics and appropriate use cases. ACID prioritizes data integrity and consistency, suitable for financial and e-commerce applications, while BASE focuses on availability and

PHP Secure File Uploads: Preventing file-related vulnerabilities.PHP Secure File Uploads: Preventing file-related vulnerabilities.Mar 26, 2025 pm 04:18 PM

The article discusses securing PHP file uploads to prevent vulnerabilities like code injection. It focuses on file type validation, secure storage, and error handling to enhance application security.

PHP Input Validation: Best practices.PHP Input Validation: Best practices.Mar 26, 2025 pm 04:17 PM

Article discusses best practices for PHP input validation to enhance security, focusing on techniques like using built-in functions, whitelist approach, and server-side validation.

PHP API Rate Limiting: Implementation strategies.PHP API Rate Limiting: Implementation strategies.Mar 26, 2025 pm 04:16 PM

The article discusses strategies for implementing API rate limiting in PHP, including algorithms like Token Bucket and Leaky Bucket, and using libraries like symfony/rate-limiter. It also covers monitoring, dynamically adjusting rate limits, and hand

PHP Password Hashing: password_hash and password_verify.PHP Password Hashing: password_hash and password_verify.Mar 26, 2025 pm 04:15 PM

The article discusses the benefits of using password_hash and password_verify in PHP for securing passwords. The main argument is that these functions enhance password protection through automatic salt generation, strong hashing algorithms, and secur

OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.OWASP Top 10 PHP: Describe and mitigate common vulnerabilities.Mar 26, 2025 pm 04:13 PM

The article discusses OWASP Top 10 vulnerabilities in PHP and mitigation strategies. Key issues include injection, broken authentication, and XSS, with recommended tools for monitoring and securing PHP applications.

PHP XSS Prevention: How to protect against XSS.PHP XSS Prevention: How to protect against XSS.Mar 26, 2025 pm 04:12 PM

The article discusses strategies to prevent XSS attacks in PHP, focusing on input sanitization, output encoding, and using security-enhancing libraries and frameworks.

PHP Interface vs Abstract Class: When to use each.PHP Interface vs Abstract Class: When to use each.Mar 26, 2025 pm 04:11 PM

The article discusses the use of interfaces and abstract classes in PHP, focusing on when to use each. Interfaces define a contract without implementation, suitable for unrelated classes and multiple inheritance. Abstract classes provide common funct

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)