rfc:class_name_literal_on_object

PHP RFC: Allow ::class on objects

Introduction

The Foo\Bar::class syntax has been introduced in PHP 5.5 to allow fetching a class name as a string, in a way that respects context-dependent name resolution rules and is understood by IDEs. As it is syntactically similar to a class constant access, programmers intuitively expect the syntax $object::class to work as well and provide the same result as get_class($object). This RFC proposes to allow that syntax.

The original rationale for not allowing the $object::class syntax was that Foo\Bar::class is resolved at compile-time, which is not possible for $object::class. However, this premise is already incorrect for two cases: First, static::class is always resolved at runtime, equivalent to get_called_class(). Second, self::class and parent::class are also sometimes resolved at runtime, for example in closures.

Overall I think that $object::class has a well-defined meaning, and programmers familiar with the Foo\Bar::class syntax generally expect it to be available by symmetry with the general $object::CONST_NAME syntax. Not allowing the syntax is more surprising than allowing it.

Proposal

$object::class is already permitted on the syntax level, but currently throws a compile error. This error will be removed when used in a normal expression context. However, $object::class will remain forbidden inside a constant expression context (as objects cannot be created there).

If $object is an object, then $object::class returns get_class($object). Otherwise it throws a TypeError exception.

$object = new stdClass;
var_dump($object::class); // "stdClass"
 
$object = null;
var_dump($object::class); // TypeError

Open Question: Additionally, it would be possible to also allow $object to be string, in which case the string would be returned verbatim. This would be consistent with the $className::CONST_NAME syntax. I'm not sure whether we should do that, as I can't imagine a context in which this would be useful, and the fact that the class name is not validated or loaded might be more unexpected here than usual.

Backward Incompatible Changes

There are no backwards incompatible changes.

Vote

Yes/No.

rfc/class_name_literal_on_object.txt · Last modified: 2020/01/09 19:57 by nikic