On Thu, May 16, 2024 at 1:32 PM Patrik Václavek <patr...@email.cz> wrote:

> 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.
>

Since this throws, I'm struggling to understand how this would replace any
usages of `instanceof` other than `if (!($var instanceof Foo)) throw new
TypeError();`

Also, this is not an RFC with a page I can look at OR something in a vote,
so the subject line is a bit of a lie.

But now that I've gotten my grumps out of the way, better class specific
syntax is in general something that I think is positive and worth exploring.

Jordan

Reply via email to