整数函数参数转换

时间:2017-10-25 10:00:29

标签: php casting integer arguments

朋友。 我有以下代码:

<?php
function f(int $a)
{
    return $a;
}

f("1a"); // get 1 and produce notice
f("aaa"); // produce TypeError ;

我使用的是php 7.1

我预计,php会根据http://php.net/manual/en/language.types.string.php#language.types.string.conversion将字符串参数转换为int 并分别给我1和0。 但似乎还有其他规则,但我无法在文档中找到它。 这条规则是什么?它在哪里描述?谢谢。

1 个答案:

答案 0 :(得分:1)

我相信你在询问类型杂耍(通过php进行类型转换)。看看http://php.net/manual/en/language.types.type-juggling.php

看看下面的代码:

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 ;

您在当前代码中使用的方式是函数参数类型声明。有关详细信息,请查看http://php.net/manual/en/functions.arguments.php#functions.arguments.type-declaration

来自PHP DOC:

  

类型声明允许函数在调用时要求参数具有某种类型。如果给定值的类型不正确,则会生成错误:在PHP 5中,这将是可恢复的致命错误,而PHP 7将引发TypeError异常。

     

要指定类型声明,应在参数名称前添加类型名称。如果参数的默认值设置为NULL,则可以使声明接受NULL值。