简体   繁体   中英

PHP7 - Can type hinting be trusted?

I have recently began to look into the new type hinting which was introduced in PHP 7 and found that it was a really nice and useful addition to add to some of my application therefore I have gone to do so however I have a question regarding argument and return type hinting.

So say I have a basic function which performs mathematics on two arguments and returns an integer.

function addTwo(int $a, int $b): int {
   return $a + $b;
}

The expected arguments should be integers and we should hopefully receive an integer value from the function, however is this always guaranteed or should there be further validation carried out within the function such as is_int to ensure both arguments are integers?

It depends on the conditions. For example, in your example to transfer lines will not succeed, but the pass float - no problem, it will be silently converted to int.

You must write declare(strict_types=1);

strict_types=1 can only apply to a file that directly declares it on its first line, no way around that.

Strict typing also has an effect on return type declarations. In the default weak mode, returned values will be coerced to the correct type if they are not already of that type. In strong mode, the returned value must be of the correct type, otherwise a TypeError will be thrown.

Returning values

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM