Static in combination with anonymous class does not behave as expected
Nobody has claimed this yet.
- Dominant language
- XML
- Stars
- 596
- Forks
- 890
- Avg merge
- 1d 15h
- Merged PRs (30d)
- 55
Description
Description
The following code:
<?php
function createTestClass() {
$test = new class() {
static public $initialised = false;
static public function __init() {
if (self::$initialised) {
throw new Exception("Already initialised.");
}
self::$initialised = true;
}
};
$test::__init();
}
createTestClass();
createTestClass();
Resulted in this output (see here):
PHP Fatal error: Uncaught Exception: Already initialised. in /Users/marco/Desktop/script.php:9
Stack trace:
#0 /Users/marco/Desktop/script.php(16): class@anonymous::__init()
php/php-src#1 /Users/marco/Desktop/script.php(20): createTestClass()
php/php-src#2 {main}
thrown in /Users/marco/Desktop/script.php on line 9
Fatal error: Uncaught Exception: Already initialised. in /Users/marco/Desktop/script.php:9
Stack trace:
#0 /Users/marco/Desktop/script.php(16): class@anonymous::__init()
php/php-src#1 /Users/marco/Desktop/script.php(20): createTestClass()
php/php-src#2 {main}
thrown in /Users/marco/Desktop/script.php on line 9
But I expected this output instead:
I'm not sure whether this is by design or really a bug.
The documentation makes no mention of the usage of static with anonymous classes.
However, I do not expect that behaviour since I'm literally creating a new class (new class()), so why should it share its static variables with other "instances" (not class instance here) of the same class?
PHP Version
8.1.11
Operating System
Irrelevant
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the reproduction in the issue body and review the PHP documentation for anonymous classes, static properties, and static methods. Compare the documented behavior with the PHP 8.1.11 example; done means the intended behavior is clarified and the relevant documentation gap or defect has a clear resolution.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- php
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 28/100