rfc:get_class_disallow_null_parameter

This is an old revision of the document!


PHP RFC: get_class() disallow null parameter

Introduction

When null is passed as the parameter to get_class() inside a class context, the behaviour of the function can be highly surprising,

class Foo
{
    function bar($repository)
    {
        $result = $repository->find(100);
 
        echo get_class($result);
    }
}

If $result contains a valid object returned from the repository, the output will be of the class name of the type of $result.

If $result contains null, the output will be of the class context where get_class() was called from, in this case “Foo”.

This feature violates the Principle of least astonishment: “if a necessary feature has a high astonishment factor, it may be necessary to redesign the feature.”

Proposal

Disallow null being passed to the function as a valid parameter.

I.e. the valid ways to call the function will be:

  • without any parameter.
  • with an object as the parameter.

Those two options will continue to have the same behaviour they currently have.

Backward Incompatible Changes

Most people won't see a BC break, as for the majority of people, passing null to this function is not a desired behaviour.

For people who do deliberately pass null to the function they will need to refactor their code from:

$x = get_class($some_value_that_may_be_null);

to:

if ($some_value_that_may_be_null === null) {
    $x = null;
}
else {
    $x = get_class($some_value_that_may_be_null);
}

Proposed PHP Version(s)

7.2

Proposed Voting Choices

The voting question will be “Should the get_class() function be changed to disallow null being passed as a parameter?” with yes/no being the options. As it is not a language or syntax change, the vote will pass if 50%+1 vote yes.

null vs default param

When this topic was discussed before, it came as a surprise to some people that PHP can tell the difference between passing null and having a default value be null. This is perfectly possible in both internal code, as well as userland code:

function get_class($item = null)
{
    if (func_num_args() == 0) {
        return get_current_scope_name();
    }
    if ($item === null) {
        trigger_error("get_class passed null, which is not an object.");
    }
 
    if (is_object($item) == false) {
        trigger_error("value is not an object");
        return false;
    }
 
    return gettype($item);
}

Patches and Tests

Implementation

After the project is implemented, this section should contain

  1. the version(s) it was merged to
  2. a link to the git commit(s)
  3. a link to the PHP manual entry for the feature
rfc/get_class_disallow_null_parameter.1471173052.txt.gz · Last modified: 2017/09/22 13:28 (external edit)