Type hinting and void return question

Say I have a class that registers a custom post type like

class Test {
  /**
   * The custom post type slug
   *
   * @var string
   *
   * @since 1.0.0
   */
  const POST_TYPE_SLUG = 'test';

  /**
   * Register custom post type
   *
   * @since 1.0.0
   */
  public function register_test_post_type() {
    $args = array(
        'label'              => esc_html( 'Test', 'my-test' ),
        'public'             => true,
        'menu_position'      => 50,
        'supports'           => array( 'title', 'revisions' ),
        'has_archive'        => false,
        'show_in_rest'       => false,
        'publicly_queryable' => false,
        'can_export'         => true,
    );

    register_post_type( self::POST_TYPE_SLUG, $args );
  }
}

I am wondering if it’s good to use return type void in this case when I’m using the method as a callback function in a hook

$test = new Test();

add_action( 'init',  [ $test, 'register_test_post_type' ] );

Especially since register_post_type, as written in the docs will return

(WP_Post_Type|WP_Error) The registered post type object, or an error object.

In this case, should I set the return type to WP_Post_Type or void?

public function register_test_post_type() : void {}

or

public function register_test_post_type() : WP_Post_Type {}

I’m working with PHP 7.1, so void typehinting is ok.

Another thing that is a bit confusing – every time I have an action hook that does something like in the case of pre_get_posts, but doesn’t return anything, is it ok to put the return type as a void?

1 Answer
1

Callback functions for anaction hook don’t need to return anything, so based on the description here:

A void return type has been introduced. Functions declared with void
as their return type must either omit their return statement
altogether, or use an empty return statement. NULL is not a valid
return value for a void function.

void would be appropriate in this context. Note that your register_test_post_type() method does not actually return the value of register_post_type(). So while register_post_type() might return a post type object, your function doesn’t.

Leave a Comment