user8579087
user8579087

Reputation:

How does the function arguments "array", "string" and "boolean" work in 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?

Upvotes: 0

Views: 311

Answers (2)

Qirel
Qirel

Reputation: 26460

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.

Upvotes: 3

sabau
sabau

Reputation: 166

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:

Upvotes: 0

Related Questions