Re: Should I use an exception to pass an instance of my object?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



 

On October 24, 2020 9:13:44 AM UTC, Jelly Legend <jelly.legend@xxxxxxxxx> 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




[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux