Error Identifier: cast.bool
Every error reported by PHPStan has an error identifier. Here’s a list of all error identifiers. In PHPStan Pro you can see the error identifier next to each error and filter errors by their identifiers.
Code example #
<?php declare(strict_types = 1);
class Foo
{
}
$foo = new Foo();
$value = (bool) $foo;
Why is it reported? #
The expression being cast to bool has a type that cannot be meaningfully cast to a boolean. Not all types support casting to bool in a well-defined way.
In the example above, an object of class Foo is cast to bool. While PHP allows casting most values to bool, PHPStan reports this when the source type makes the cast problematic or undefined.
How to fix it #
Instead of casting the value directly, use an explicit comparison or add a method that returns a boolean:
<?php declare(strict_types = 1);
class Foo
{
+ public function isValid(): bool
+ {
+ return true;
+ }
}
$foo = new Foo();
-$value = (bool) $foo;
+$value = $foo->isValid();
How to ignore this error #
You can use the identifier cast.bool to ignore this error using a comment:
// @phpstan-ignore cast.bool
codeThatProducesTheError();
You can also use only the identifier key to ignore all errors of the same type in your configuration file in the ignoreErrors parameter:
parameters:
ignoreErrors:
-
identifier: cast.bool
Rules that report this error #
- PHPStan\Rules\Cast\InvalidCastRule [1]