PHP class instantiation from variable and use keyword

99 Views Asked by At

could I ask about one clarification? At the top of my file i used (Silex context):
use Symfony\Component\Validator\Constraints as Assert;

Lets say I have an array $asserts with asserts names as strings:

'Assert\\NotBlank()', 'Assert\\Date()'

When I'm trying to

foreach($asserts as $constraint) {
  array_push($some_other_array, new $constraint)
}

I get Class Assert\NotBlank() not found, but when I make new instance explicitly

foreach($asserts as $constraint) { 
  array_push($some_other_array, new Assert\NotBlank())
}

everything works. What am I doing wrong?

EDIT: I tried with and without () and also with full paths to classes.

SOLUTION: An array of full paths without parentheses should be used.

'Symfony\Component\Validator\Constraints\NotBlank',
'Symfony\Component\Validator\Constraints\Date'

Best Regards,
Kamil

1

There are 1 best solutions below

0
On

Try an array of:

'Assert\\NotBlank', 'Assert\\Date'

and:

array_push($some_other_array, new $constraint());

Per: dynamic class names in php