Skip to content

Latest commit

 

History

History
100 lines (80 loc) · 2.33 KB

File metadata and controls

100 lines (80 loc) · 2.33 KB

Type Hints - Why They Matter

The Problem

Code without type hints is like an API without documentation. Nobody knows:

  • What does the function expect? - Which data type should be passed?
  • What does it return? - String? Array? Object? Null?
  • When are there errors? - Only at runtime, when it's too late

Bad Practice (bad.php)

function get_post_excerpt( $post ) {
    if ( $post ) {
        return substr( $post->post_content, 0, 100 );
    }
    return null;
}

Problems:

  • $post could be anything - int, string, WP_Post, null?
  • Return value is unclear - string or null?
  • IDE can't help - no autocompletion
  • Errors only visible at runtime
  • Other developers have to read code to understand usage

Good Practice (good.php)

function get_post_excerpt( WP_Post $post ): string {
    return substr( $post->post_content, 0, 100 );
}

Benefits:

  • Clear: Expects a WP_Post object
  • Clear: Always returns a string
  • IDE shows errors immediately (before running!)
  • Autocompletion works perfectly
  • Self-documenting code

More Examples

Nullable Types

// BAD: What happens if no post is found?
function get_post_title( $id ) {
    $post = get_post( $id );
    return $post->post_title;
}

// GOOD: Explicitly states that null is possible
function get_post_title( int $id ): ?string {
    $post = get_post( $id );
    return $post ? $post->post_title : null;
}

Property Type Hints (PHP 7.4+)

// BAD: No idea what $post should be
class PostProcessor {
    private $post;
}

// GOOD: Crystal clear
class PostProcessor {
    private WP_Post $post;
}

Union Types (PHP 8.0+)

// GOOD: Function accepts ID or slug
function get_post_by_id_or_slug( int|string $identifier ): ?WP_Post {
    // ...
}

Key Takeaways

Always use type hints (parameters + return)
?Type for nullable values
Property type hints in classes
DocBlocks for arrays of objects (@return WP_Post[])
Union types when multiple types make sense

❌ Don't skip type hints - "Because it's faster"
❌ Don't fall back to mixed when you can be more specific
❌ DocBlocks are not a replacement for real type hints

IDE Support

With type hints you get:

  • ✨ Autocompletion
  • ⚠️ Immediate error indication
  • 🔍 "Go to definition" works
  • 🔄 Safe refactorings