Skip to content

Cannot set exception code for custom exception #14673

Open
@Chi-teck

Description

@Chi-teck

Description

The following code:

<?php

class Example extends \Exception {
  protected $code = 5;
}

echo '', (new Example(''))->getCode(), \PHP_EOL;
echo '0 → ', (new Example('', 0))->getCode(), \PHP_EOL;
echo '1 → ', (new Example('', 1))->getCode(), \PHP_EOL;

Resulted in this output:

  → 5
0 → 5
1 → 1

But I expected this output instead:

  → 5
0 → 0
1 → 1

There is a note about default parameters in exception constructor on php.net. However, case 2 in the above example explicitly passes the code parameter to the constructor.

Calling the constructor of class Exception from a subclass ignores the default arguments, if the properties $code and $message are already set. about default parameters in exception constructor on php.net.

PHP Version

PHP 8.2

Operating System

Debian 11

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions