PHP’s isset(). Semantics? Meh.

While I was working on the definition of the parameter set for a new WordPress REST API controller, I came across something odd. Fire up PHP’s interactive shell and see for yourself:

php > $a = array( 'b' => null );
php > echo json_encode( isset( $a['b'] ) );
false
php > echo json_encode( $a );
{"b":null}

Well to be honest, when I ask you whether something is set, I expect you to tell me if it is set, whatever its value may be. But PHP’s isset() is not implemented like that. What it will tell you is whether that thing is set, unless that thing is set as null. In that latter case, it doesn’t care that it’s set and it will tell you it isn’t set. Sounds complicated and counterintuitive? Yeah.

I would rather check myself whether I like it when that value is null.:

if ( isset( $a['b'] ) && $a['b'] !== null ) {
    // do stuff
}

PHP’s isset() works exactly like that above, whether you like it … or not.

Setting default Values for REST Controller Parameters

Extending the WP_REST_Controller class, you implement the get_collection_params() method to provide the query parameters for the collection, i.e. you define which parameters your request understands.

I was wondering whether we should, or should not, provide null as the default value for some parameters.

$params['foo'] = array(
    'default' => null, // TO DO OR NOT TO DO?
    'type' => string,
    'description' => 'Just an example',
    'sanitize_callback' => 'sanitize_text_field',
    'validate_callback' => 'rest_validate_request_arg'
);

As it turns out, if you provide null as the default value for a parameter, it’s as if no default value was provided for the parameter at all.

Why?

Your default parameters are handled in WP_REST_Server->match_request_to_handler( $request ) where the defaults are stored in an array property of the instance. But whether that default value is actually stored or not is decided like this:

foreach ( $handler['args'] as $arg => $options ) {
    if ( isset( $options['default'] ) ) {
        $defaults[ $arg ] = $options['default'];
    }
}

Considering what we have learned above, if you provide null as the default, no default value will be stored.

So do we provide null as the default for a parameter? No. You can just skip it.

References


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Share