in Php, I would like to have my exception immutable:
readonly class MyImmutableException extends Exception
{
}
as you can see its not possible, it causes fatal error as Exception is not immutable.
But I would like to have all my system immutable so bad, so is exceptions
2
Answers
You cannot do that the way you do now. It’s part of the design and it’s mentioned in "Inheritance" section of RFC for read-only classes:
So you either keep inheriting from
Exception
class or have read-only attribute applied.Please note, that it might not be necessary to involve the core
Exception
class here at all, as it should be sufficient for most of the cases to just to create own, readonly, base class for your exceptions. Then, as long as your exception class (so base or its children, if base isabstract
) implements Throwable contract, you should be good to roll. And you can even just cloneException
class code for your base to not reinvent the wheel.You could do something like this and define your exception to not have any input, so there is nothing to change:
You could also define some defaults if you do want that. If you dont have any setters, no-one can change it:
This is a bad idea. You might have a good reason, but as a rule this is a bad rule. I suggest you research the Open/Closed principle.