php / php/php-src

Incorrect `ReflectionClass::getNamespaceName` for anonymous class

Open
#12,895 11 comments 0 reactions 0 assignees View on GitHub

@ndossche is already working on this.

Since Dec 8, 2023.

  • #12907 by @ndossche — open
Bug Category: Engine Extension: reflection OS: Windows Status: Verified
Dominant language
C
Stars
40.4k
Forks
8.1k
Avg merge
2d 13h
Merged PRs (30d)
96

Description

Description

The following code:

<?php

namespace Foo {
    interface InterfaceFoo {}
}

namespace Bar {
    new class implements \Foo\InterfaceFoo {};
}

namespace {
    foreach (get_declared_classes() as $class) {
        if (!str_contains($class, '@anonymous')) {
            continue;
        }
        echo 'Class: ', $class, PHP_EOL;
        echo 'Namespace: ', (new ReflectionClass($class))->getNamespaceName(), PHP_EOL;
    }
}

Resulted in this output:

Class: Foo\InterfaceFoo@anonymousD:\a\php-anonymous-class-namespace\php-anonymous-class-namespace\test.php:8$0
Namespace: Foo\InterfaceFoo@anonymousD:\a\php-anonymous-class-namespace\php-anonymous-class-namespace

at Windows and

Class: Foo\InterfaceFoo@anonymous/home/runner/work/php-anonymous-class-namespace/php-anonymous-class-namespace/test.php:8$0
Namespace: Foo

at Ubuntu

But I expected this output instead:

Class: Foo\InterfaceFoo@anonymousD:\a\php-anonymous-class-namespace\php-anonymous-class-namespace\test.php:8$0
Namespace: Bar

Reproduced at https://github.com/werlos/php-anonymous-class-namespace (see the only action there).

PHP Version

8.3.0

Operating System

No response

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

Start with the supplied PHP reproducer and the ReflectionClass::getNamespaceName() entry point. Compare its output on Windows and Ubuntu with the expected namespace, then inspect linked pull request #12907 before making changes. Done means the anonymous class reports Bar consistently.

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
Clearly specified
Newbie friendliness
30/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.