Always be explicit and consistent when handling null values to improve code clarity and prevent subtle bugs. This applies to null checks, nullable type declarations, and function parameters.
Always be explicit and consistent when handling null values to improve code clarity and prevent subtle bugs. This applies to null checks, nullable type declarations, and function parameters.
For null checks:
null !== $variable
or $variable === null
instead of just if ($variable)
For type declarations:
?
) for parameters and return types that can be nullFor function parameters:
// Bad
public function doSomething($client)
{
if ($client) {
// ...
}
}
// Good
public function doSomething(?ClientInterface $client = null): ?string
{
if (null !== $client) {
// ...
}
}
This pattern makes intent clear, improves static analysis capabilities, and provides better autocomplete support in IDEs. It also prevents confusion between false, empty strings, zero, and null values in conditionals.
Enter the URL of a public GitHub repository