Introduction

*************




This RFC proposes a new feature in PHP: type guards for classes (or
interfaces). This feature aims to simplify and standardize the process of 
verifying that a variable is an instance of a specific class, enhancing code
readability and reducing boilerplate code.




Motivation

*************





Currently, in PHP, to ensure that a variable is an instance of a specific 
class, developers need to use the `instanceof` operator and manually throw
an exception if the check fails. This results in repetitive boilerplate code
scattered throughout the codebase. A new syntax, `(ClassName) $variable`, is
proposed to streamline this process by performing an instanceof check and 
throwing a `TypeError` if the variable is not an instance of the specified
class.




Proposal

***********





Introduce a new type guard syntax for classes:




```php

(Foo) $variable;

```




This syntax will internally perform the following operations:




1. Check if `$variable` is an instance of `Foo`.

2. If the check fails, throw a `TypeError` with a message indicating the 
expected and actual types.




Example:

Consider the following class definition:




```php

class Foo {

   // class definition

}

```




To ensure a variable is an instance of `Foo`, instead of writing:




```php

if (!$variable instanceof Foo) {

    throw new TypeError('Expected instance of Foo, got ' . gettype($
variable));

}

```




Developers can use the new type guard syntax:




```php

(Foo) $variable;

```




Backward Compatibility

***************************





This feature introduces new syntax and does not affect existing code. It is
fully backward-compatible, as it does not modify or deprecate any existing
functionality.

Reply via email to