dongyi7669 2017-09-26 07:17
浏览 28
已采纳

函数参数“array”,“string”和“boolean”如何在PHP中工作?

I'm making a program that will only accept a boolean value as parameter. I thought I could instanceof to do this, but it does not work as I expected.

function test (boolean $param) {
    echo $param;
}
test(true);

When I use it in my program, I get following error message:

Argument 1 passed to test() must be an instance of boolean

Is instanceof the right method to do this and how does it work?

  • 写回答

2条回答 默认 最新

  • duanjing7298 2017-09-26 07:42
    关注

    As per the manual on type-declarations, it's stated that you need to use bool instead of boolean when type-declaring for a boolean value. This also requires PHP-version 7.0.0 or higher.

    function test (bool $param) {}
    test(true);
    

    If you are on a PHP version lower than 7.0.0, you cannot use the boolean type-declaration at all. However, you can check if a boolean argument was supplied by using is_bool($param), then return false, null or throw an exception instead, and deal with it that way. You can also issue a user-warning (by trigger_error()) if you think its appropriate.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容