Re: Should I use an exception to pass an instance of my object?
| From: | Ashley Sheridan | Date: | Sat, 24 Oct 2020 11:59:15 +0000 |
| Subject: | Re: Should I use an exception to pass an instance of my object? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-327344@lists.php.net to get a copy of this message | ||
On October 24, 2020 9:13:44 AM UTC, Jelly Legend <jelly.legend@gmail.com> wrote:
>I'm facing a situation where I want to use an exception in my
>__construct
>method to notify the caller that the input data is invalid. But I
>because I
>want to avoid having to use a static constructor method or validate the
>data before the __construct call I thought I would just modify the data
>based on my needs and at the very end of __construct throw a custom
>exception what holds the instance of $this so it can still be used at
>the
>callers side.
>
>Example: https://3v4l.org/pbIWR
>
>Should I do it?
Personally for these sorts of things I tend to do only very basic validation in a constructor if
it's ever needed, and directly throw an exception there specific to the class the constructor
is in. PHP can do all the type checking for you (it's much better in PHP 7.1 and up) and you
can wrap calls to constructors in a try/catch block to handle them better and give the user the
error output you need them to have, whilst logging more full information.
Thanks,
Ash