use Symfony\Component\OptionsResolver\OptionsResolver; $options = [ 'foo' => 'bar' ]; $resolver = new OptionsResolver(); $resolver->setDefaults($options); $resolver->resolve(['foo' => 'baz']); // returns ['foo' => 'baz'] $resolver->resolve([]); // returns ['foo' => 'bar']
use Symfony\Component\OptionsResolver\OptionsResolver; $options = [ 'foo' => null, 'bar' => 123 ]; $resolver = new OptionsResolver(); $resolver->setDefaults($options); $resolver->resolve(['foo' => 'baz']); // returns ['foo' => 'baz', 'bar' => 123] $resolver->resolve(['bar' => 456]); // returns ['foo' => null, 'bar' => 456] $resolver->resolve([]); // returns ['foo' => null, 'bar' => 123]In this example, the setDefaults method is used to set the default values of the "foo" option to null and the "bar" option to 123. When calling the resolve method with an array that contains a value for "foo", that value is returned along with the default value of "bar". When calling the resolve method with an array that contains a value for "bar", that value is returned along with the default value of "foo". When calling the resolve method without passing any options, both options use their default values. Overall, the OptionsResolver class is a useful tool in validating and setting default values of options in PHP.