Jump to content

catch with type intersection


rick645

Recommended Posts

$ php -v | grep cli
PHP 8.1.2-1ubuntu2.14 (cli) (built: Aug 18 2023 11:41:11) (NTS)


$ cat catch.php
<?php
interface Err {
    function getExitCode();
}

function main(Throwable&Err $throwable1)  { #ID1
    try {
        throw $throwable1;
    } catch (Throwable&Err $throwable2) { #ID2
        echo $throwable2->getExitCode() . PHP_EOL;
    }
}

$throwable = new class extends Exception implements Err {
    function getExitCode() {
        return 123;
    }
};

main($throwable);

I highlight a few lines

$ grep ID catch.php
function main(Throwable&Err $throwable1)  { #ID1
    } catch (Throwable&Err $throwable2) { #ID2

So let's try

$ php catch.php
PHP Parse error:  syntax error, unexpected token "&", expecting ")" in /tmp/catch.php on line 10

Why?

mmmhhh...

I try to remove Throwable& from the line #ID2

$ grep ID2 catch.php
    } catch (Err $throwable2) { #ID2
$ php catch.php
123

Works!!!

So it seems that catch doesn't accept the type intersection.
Why?
Is there any official documentation that talks about it?

Edited by rick645
Link to comment
Share on other sites

The documentation says you can combine using |. 

Quote

As of PHP 7.1.0, a catch block may specify multiple exceptions using the pipe (|) character. This is useful for when different exceptions from different class hierarchies are handled the same.

Throwable&Err is redundant anyway.  Anything that is thrown must implement throwable, so just specifying Err is all you need.

 

Link to comment
Share on other sites

You cannot catch with type intersection - only a type union, which isn't really a union but more like a syntax meaning "or".

If you want a type intersection then use a named class. But in your case, kicken's right: all you actually care about is the Err and its getExitCode method anyway.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.