【问题标题】:integer function argument conversion整数函数参数转换
【发布时间】:2017-10-25 10:00:28
【问题描述】:

朋友。 我有以下代码:

<?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。 但似乎还有其他规则,但我在文档中找不到。 这是什么规则,它在哪里描述?谢谢。

【问题讨论】:

    标签: php casting integer arguments


    【解决方案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 文档:

    类型声明允许函数在调用时要求参数为特定类型。如果给定值的类型不正确,则会产生错误:在 PHP 5 中,这将是一个可恢复的致命错误,而 PHP 7 将抛出 TypeError 异常。

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

    【讨论】:

    • 好的,我明白,铸造机制不同于标准的 php 类型铸造。(类型杂耍)。谢谢,@Chetan Ameta
    猜你喜欢
    • 2015-05-08
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 2013-01-24
    • 1970-01-01
    • 2015-08-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多