Thank you, the example I put was mostly just for showing that it is valid to return an instance of an object even though the constructor failed. I was thinking of implementing this for a ShoppingCart class where I load the products from the db to. I use the same public methods of the class to load the products and they contain validation. So it can happen that the cart from the db has more quantity than there is stock available but this information is known to me only after / in instantiation. I could validate the items beforehand but I wanted to avoid double looping since I don't consider stock change a valid enough reason, but I still need the information to notify the end user about the cart changes without some global hackery. I ended up implementing a didChange method that can be used to retrieve the information I was looking to pass through the exception. Although, it was an interesting thought, to use an exception in the constructor to pass the object itself back to the client code since the state of the object was not considered invalidated enough to stop execution but still invalid enough to notify the caller further action should be taken.
V V sob., 24. okt. 2020 ob 13:59 je oseba Ashley Sheridan <ash@xxxxxxxxxxxxxxxxxxxx> napisala:
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