drol55885602 2017-06-17 16:26
浏览 23
已采纳

PHP Nullable Types无法按预期工作

I wanted to know if the new feature of nullable types can be used to change the syntax in this working function from

function getCustomerId($id = null)
{
    return $id ?: 2;
}

echo getCustomerId();

to something like this which isn't working for me. I get the error for too few arguments.

function getCustomerId(?int $id)
{
    return $id ?: 2;
}

echo getCustomerId();

so that basically if the argument is not provided it returns 2, but if the argument is provided it returns that argument.

  • 写回答

1条回答 默认 最新

  • duanping1920 2017-06-17 16:53
    关注

    Yer kinda confusing the concept of optional arguments with the concept of nullable ones.

    An optional arguments means you don't need to pass it cos it's optional.

    A nullable argument means that whilst the argument needs to be of a certain type, that null is also valid (where it wouldn't be if it wasn't nullable). Nullability doesn't mean you don't need to pass anything; you still do. It can just be null.

    If you want to have an integer argument which is optional and considered null if not passed, then combine yer two examples:

    function getCustomerId(?int $id=null)
    {
        return $id ?: 2;
    }
    

    Ref: PHP > New Features > Nullable types

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么