Re: [RFC] [Vote] Type Guards for Classes
| From: | Jordan LeDoux | Date: | Fri, 17 May 2024 00:11:50 +0000 |
| Subject: | Re: [RFC] [Vote] Type Guards for Classes | ||
| References: | 1 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-123328@lists.php.net to get a copy of this message | ||
On Thu, May 16, 2024 at 1:32 PM Patrik Václavek <PaTrOnY@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