Skip to content

[DependencyInjection] Method signatures with constants defined at runtime break compilation #34053

@m-vo

Description

@m-vo

Description
Services cannot contain constants in method signatures that are defined at runtime. Doing so results in errors during container compilation here and here:

Error: Method ReflectionMethod::__toString() must not throw an exception, caught ErrorException: Warning: Use of undefined constant SOME_CONSTANT - assumed 'SOME_CONSTANT' (this will throw an Error in a future version of PHP)

Is this a (known) limitiation or should this use case be supported?

Background: In Contao we're dealing with some legacy classes that utilize constants in method signatures (see reproducer A). Developers are inheriting from these classes and potentially registering them as services - which fails. Or they might have enabled automatic loading of services (via App\: resource: '../src/*') which had silently worked but suddenly produces a subtle, hard to find error as soon as a class with said method signatures is used. 🤔

How to reproduce (A)

  1. Create a class/service Bar that defines a constant at runtime:
class Bar
{
    public function __construct()
    {
        define('SOME_CONSTANT', 1);
    }
}
  1. Create a class/service Foo that uses that constant in a method signature: (Inheriting from Bar is optional but would be a typical use case.)
class Foo extends Bar
{
    public function foo($a = SOME_CONSTANT) { 
        // ...
    }
}
  1. Build the container.

How to reproduce (B)
In fact the same error will occur for this simplified use case:

  1. Create a class/service FooBar
class FooBar
{
    public function __construct()
    {
        define('SOME_CONSTANT', 1);
    }

    public function fooBar($a = SOME_CONSTANT)
    {
    }
}
  1. Build the container.

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