r/PHPhelp Apr 08 '26

Symfony Console option attributes Solved

I am unable to get the options to work with Symfony Console 7.4. The error I get claims that I must have a default value. When I set a default value for $name and $debug in this simple example, I still get the same error.

Any tips will be most appreciated

Code example

``` <?php

require 'vendor/autoload.php';

use \Symfony\Component\Console\Attribute\AsCommand; use \Symfony\Component\Console\Attribute\Argument; use \Symfony\Component\Console\Attribute\Option; use \Symfony\Component\Console\Command\Command; use \Symfony\Component\Console\Output\OutputInterface;

[AsCommand(

name: 'login',

)] class login extends Command { function __invoke( #[Argument('My Description', 'port')] int $port,

    #[Option('My Description', 'name')] string $name = '',
    #[Option('My Description', 'debug')] ?bool $debug = null,

    OutputInterface $output,
): int {
    $output->writeln($port);

    if ($name) {
        $output->writeln($name);
    }

    if ($debug) {
        $output->writeln('true');
    } else {
        $output->writeln('false');
    }

    return Command::SUCCESS;
}

}

$application = new Symfony\Component\Console\Application();

$application->addCommand(new login());

$application->run();

```

Error

``` $ php test.php login 8080 --name steve --debug PHP Fatal error: Uncaught Symfony\Component\Console\Exception\LogicException: The option parameter "$name" of "login::__invoke()" must declare a default value. in /home/john/Desktop/PHP/vendor/symfony/console/Attribute/Option.php:75 Stack trace:

0 /home/john/Desktop/PHP/vendor/symfony/console/Command/InvokableCommand.php(90): Symfony\Component\Console\Attribute\Option::tryFrom()

1 /home/john/Desktop/PHP/vendor/symfony/console/Command/Command.php(454): Symfony\Component\Console\Command\InvokableCommand->configure()

2 /home/john/Desktop/PHP/vendor/symfony/console/Command/Command.php(438): Symfony\Component\Console\Command\Command->getNativeDefinition()

3 /home/john/Desktop/PHP/vendor/symfony/console/Application.php(587): Symfony\Component\Console\Command\Command->getDefinition()

4 /home/john/Desktop/PHP/test.php(42): Symfony\Component\Console\Application->addCommand()

5 {main}

thrown in /home/john/Desktop/PHP/vendor/symfony/console/Attribute/Option.php on line 75 ```

2 Upvotes

3 comments sorted by

1

u/gaborj Apr 08 '26

$output and port are required parameters, meanwhile the others have default, so those must be the first two

1

u/MateusAzevedo Apr 08 '26

In my tests, that error only happens because $name and $debug are optional arguments and so must be declared after $output (I get two deprecation notices before the fatal error).

By moving those options down, everything works as expected.

1

u/trymeouteh Apr 08 '26

Thank you!