rick645 Posted September 8, 2023 Share Posted September 8, 2023 (edited) $ 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 September 8, 2023 by rick645 Quote Link to comment Share on other sites More sharing options...
kicken Posted September 8, 2023 Share Posted September 8, 2023 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. Quote Link to comment Share on other sites More sharing options...
requinix Posted September 8, 2023 Share Posted September 8, 2023 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. Quote Link to comment Share on other sites More sharing options...
rick645 Posted September 8, 2023 Author Share Posted September 8, 2023 Redundant? mmmhhh... } catch (InvalidArgumentException&Err $throwable) { Catches exceptions that extend InvalidArgumentException and implement Err. Very comfortable, I would say!!! Wouldn't it be right to propose it for a future version of php? Quote Link to comment Share on other sites More sharing options...
requinix Posted September 8, 2023 Share Posted September 8, 2023 I think you're misusing inheritance and interfaces, but sure, go ahead and try the RFC process if you want. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.