PrimuS
PrimuS

Reputation: 2683

Create new Object by string variable in Symfony3/PHP

I send variables to my route via an ajax post. Based on the value of my type value I create a new Object, like this:

if($request->get('type') === 'HardwareType'){
    $e = new HardwareType();
}else if($request->get('type') === 'SetupType'){
    $e => new SetupType();
}else{
    new NotFoundHttpException();
}

This gets out of hand quickly even with a switch I think its still "ugly". Is there any way I could do sth. like this:

$e = new $request->get('type')();

Any hint appreciated

EDIT I use the class(es) with this use AppBundle\Entity\HardwareType; etc.

Upvotes: 1

Views: 663

Answers (2)

delboy1978uk
delboy1978uk

Reputation: 12365

Just use an associative array! Define the acceptable classes, so that other types of class you don't want to allow can't be instantiated!

Then just check the key is in the array, and if so create a new Whatever()!

$types = [
    'HardwareType' => HardwareType::class,
    'etc' => SomeOther::class
];

$getVar = $request->get('type');

// So all you need do is 
if (array_key_exists($getVar, $types)) {
    $e = new $types[$getVar]();
} else {
    throw new NotFoundHttpException();
}

Upvotes: 2

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35973

you can do this:

$e = $request->get('type');
$class = new $e();

If you need you can add the path or the class like this:

$e = 'AppBundle\Entity\' . $request->get('type');

Obviously you need to add use at the begin of the file and you can check before the new if the class exist or not

Like this:

if (!class_exists($e)) {
   //exception
}

Upvotes: 3

Related Questions