Closed
Description
Whenever a class has a method that uses an anonymous class that itself has a method that matches the name of the containing class, PHP_CodeSniffer reports that the class uses an old style constructor.
<?php
class Nested {
public function getAnonymousClass() {
return new class() {
public function nested() {
echo 'In method nested!';
}
};
}
}
$nested = (new Nested())->getAnonymousClass();
$nested->nested();
Running with php Nested.php
shows:
In method nested!
Running PHP_CodeSniffer, it reports that an old style constructor is used:
FILE: Nested.php
----------------------------------------------------------------------
FOUND 1 ERROR AFFECTING 1 LINE
----------------------------------------------------------------------
8 | ERROR | PHP4 style constructors are not allowed; use
| | "__construct()" instead
| | (Generic.NamingConventions.ConstructorName.OldStyle)
----------------------------------------------------------------------
Had an old style constructor been used, the line In method nested!
should have appeared in the output twice, once for the constructor on line 15, and once for the method call on line 16.
Based on the error message, ConstructorNameSniff::processTokenWithinScope is to blame. From what I can see, it uses the name of the containing class because the anonymous class does not have a name.
Used .phpcs.xml file:
<?xml version="1.0"?>
<ruleset>
<rule ref="Generic.NamingConventions.ConstructorName.OldStyle"/>
<file>Nested.php</file>
<arg name="encoding" value="UTF-8"/>
</ruleset>
Used PHPCS 3.3.2.