Skip to content

#[\Attribute] validation should error on trait/interface/enum/abstract class #19153

Closed

Description

@DanielEScherzer

Description

See https://3v4l.org/99PhY

<?php

#[Attribute]
enum DemoEnum {}

#[Attribute]
trait DemoTrait {}

#[Attribute]
abstract class DemoAbstract {}

#[Attribute]
interface DemoInterface {}

#[DemoEnum]
#[DemoTrait]
#[DemoAbstract]
#[DemoInterface]
function usesWrongAttrib() {}

$r = new ReflectionFunction( 'usesWrongAttrib' );
$a = $r->getAttributes();
var_dump( $a );
foreach ( $a as $attrib ) {
    try {
        $attrib->newInstance();
    } catch ( Error $e ) {
        echo get_class( $e ) . ": " . $e->getMessage() . "\n";
    }
}

currently outputs

array(4) {
  [0]=>
  object(ReflectionAttribute)#2 (1) {
    ["name"]=>
    string(8) "DemoEnum"
  }
  [1]=>
  object(ReflectionAttribute)#3 (1) {
    ["name"]=>
    string(9) "DemoTrait"
  }
  [2]=>
  object(ReflectionAttribute)#4 (1) {
    ["name"]=>
    string(12) "DemoAbstract"
  }
  [3]=>
  object(ReflectionAttribute)#5 (1) {
    ["name"]=>
    string(13) "DemoInterface"
  }
}
Error: Cannot instantiate enum DemoEnum
Error: Cannot instantiate trait DemoTrait
Error: Cannot instantiate abstract class DemoAbstract
Error: Cannot instantiate interface DemoInterface

But we should have compile-time errors instead.

Activity

  1. DanielEScherzer commented on Jul 16, 2025

    @DanielEScherzer
    MemberAuthor

    Cross link #15731 which had similar reasoning

  2. changed the title [-]Attribute validation should error on trait/interface/enum/abstract class[/-] [+]#[\Attribute] validation should error on trait/interface/enum/abstract class[/+] on Jul 17, 2025
  3. added a commit that references this issue on Aug 11, 2025
  4. added a commit that references this issue on Aug 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions