Skip to content

Class not found when defined after use, if it contains a __toString method #12320

@tobia

Description

@tobia

Description

The following code:

<?php

new A();

echo "OK";

class A {
    public function __toString() {
        return "A";
    }
}

Resulted in this output:

Uncaught Error: Class "A" not found

But I expected this output instead:

OK

Here is a simple way to test multiple versions in Bash:
for ver in 7.4.33 8.0.0alpha1 8.2.10 8.2.11RC1 8.3.0RC2; do echo $ver:; docker run --rm php:$ver -r 'new A; echo "OK\n"; class A { function __toString() { return "A"; } }'; echo; done

Result:

7.4.33:
OK

8.0.0alpha1:

Fatal error: Uncaught Error: Class 'A' not found in Command line code:1
Stack trace:
#0 {main}
  thrown in Command line code on line 1

8.2.10:

Fatal error: Uncaught Error: Class "A" not found in Command line code:1
Stack trace:
#0 {main}
  thrown in Command line code on line 1

8.2.11RC1:

Fatal error: Uncaught Error: Class "A" not found in Command line code:1
Stack trace:
#0 {main}
  thrown in Command line code on line 1

8.3.0RC2:

Fatal error: Uncaught Error: Class "A" not found in Command line code:1
Stack trace:
#0 {main}
  thrown in Command line code on line 1

As you can see, this bug was introduced in the 8.x branch, because all 8.x versions are affected, from the first alpha to the latest RCs, including all stable versions I tried. 7.x and earlier are unaffected.

I did not test if other magic methods have the same effect.

PHP Version

8.x

Operating System

No response

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