php / php/php-src

Cannot set exception code for custom exception

Open
#14,673 12 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Bug Status: Needs Triage
Dominant language
C
Stars
40.4k
Forks
8.1k
Avg merge
2d 13h
Merged PRs (30d)
96

Description

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

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

The report provides a PHP 8.2 reproducer involving a custom Exception subclass, the Exception constructor, and getCode(). Start by locating those entry points in php-src and reproducing all three constructor calls. Done means an explicitly passed code of 0 is preserved while the other demonstrated outputs remain correct.

Written by the indexing model from the issue text.

Assessment

Tech stack
php
Domain
backend
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.