2017-09-26 07:17 阅读 27


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;

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 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) {}

    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.

    点赞 评论 复制链接分享
  • douti6740 douti6740 2017-09-26 07:47

    According to the documentation you will find that, depending on PHP version, the available options changes: type-declaration

    If you are using PHP 7.0 you should use bool, aliases for scalar types are not supported in type declarations, they will be interpreted as Class or interface names.

    If you are using PHP 5.0 - PHP 5.6 you should use objects that defines the parameters types you need to hint, you will find more information about type hinting here:

    点赞 评论 复制链接分享