Functions that return different types are:
- Unpredictable - Callers don't know what to expect
- Error-prone - Easy to miss a case
- Hard to test - Must test all return paths
- Confusing -
0vsfalsevsnullvs-1
function get_user_posts($user_id) {
if (!$user_id) {
return false;
}
$posts = get_posts(['author' => $user_id]);
if (empty($posts)) {
return null;
}
if (count($posts) === 1) {
return $posts[0]; // WP_Post
}
return $posts; // array
}Returns 4 different types!
function get_user_posts( int $user_id ): array {
return get_posts( [ 'author' => $user_id ] ) ?: [];
}function find_post( int $id ): ?WP_Post {
$post = get_post( $id );
return $post instanceof WP_Post ? $post : null;
}class ValidationResult {
public function __construct(
private readonly bool $is_valid,
private readonly array $errors = []
) {}
}function create_post( string $title ): int|WP_Error {
// Always int or WP_Error, never false or null
}✅ One function = one return type
✅ Use arrays for collections (never array|object)
✅ Use null for "not found"
✅ Use exceptions for errors
✅ Use Result objects for complex returns
✅ Document return type with PHPDoc
❌ Don't return array|false|null
❌ Don't return object|array
❌ Don't return int|false (0 is falsy!)
❌ Don't mix success/error return types