Reputation: 31
friends. I have following code:
<?php
function f(int $a)
{
return $a;
}
f("1a"); // get 1 and produce notice
f("aaa"); // produce TypeError ;
I use php 7.1
I expected, that php will convert string argument to int according the http://php.net/manual/en/language.types.string.php#language.types.string.conversion and give me 1 and 0 respectively. But seems, that there are another rules, but i can`t find it in documentation. What is this rules and Where does it described? thank you.
Upvotes: 1
Views: 235
Reputation: 7896
I believe you are asking about type juggling (type conversion by php). have a look at http://php.net/manual/en/language.types.type-juggling.php
have a look on below piece of code:
echo (int) '1a'; //print 1
echo (int) 'aaa'; //print 0
function f($a)
{
return (int) $a;
}
echo f("1a"); // print 1
echo f("aaa"); // print 0 ;
The way you used in current code is function argument type declarations. have a look at http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration for more detail.
From PHP DOC:
Type declarations allow functions to require that parameters are of a certain type at call time. If the given value is of the incorrect type, then an error is generated: in PHP 5, this will be a recoverable fatal error, while PHP 7 will throw a TypeError exception.
To specify a type declaration, the type name should be added before the parameter name. The declaration can be made to accept NULL values if the default value of the parameter is set to NULL.
Upvotes: 1