-
-
Notifications
You must be signed in to change notification settings - Fork 9.7k
Description
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)
- Create a class/service
Bar
that defines a constant at runtime:
class Bar
{
public function __construct()
{
define('SOME_CONSTANT', 1);
}
}
- Create a class/service
Foo
that uses that constant in a method signature: (Inheriting fromBar
is optional but would be a typical use case.)
class Foo extends Bar
{
public function foo($a = SOME_CONSTANT) {
// ...
}
}
- Build the container.
How to reproduce (B)
In fact the same error will occur for this simplified use case:
- Create a class/service
FooBar
class FooBar
{
public function __construct()
{
define('SOME_CONSTANT', 1);
}
public function fooBar($a = SOME_CONSTANT)
{
}
}
- Build the container.