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 {}


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?


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.

| improve this answer | |
  • Ok, thanks for setting my mind at ease (plus I don't have to rewrite tons of void return type hints in my code :D). I'll accept the answer in 8 min :) – dingo_d Jul 5 '18 at 11:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.