skip to Main Content

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


  1. 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:

    Similarly how overriding of readonly properties works, a readonly class can only extend a readonly parent.

    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 is abstract) implements Throwable contract, you should be good to roll. And you can even just clone Exception class code for your base to not reinvent the wheel.

    Login or Signup to reply.
  2. You could do something like this and define your exception to not have any input, so there is nothing to change:

    class MyImmutableException extends Exception
    {
        public function __construct(){
            parent::__construct();
        } 
    }
    

    You could also define some defaults if you do want that. If you dont have any setters, no-one can change it:

    class MyImmutableException extends Exception
    {
        private const MESSAGE = 'I am an example';
        private const CODE = 123;
    
        public function __construct(){
            parent::__construct(
                self::MESSAGE,
                self::code
            );
        } 
    }
    

    I would like to have all my system immutable so bad, so is exceptions

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search