简体   繁体   English

在Symfony3 / PHP中通过字符串变量创建新对象

[英]Create new Object by string variable in Symfony3/PHP

I send variables to my route via an ajax post. 我通过ajax发布将变量发送到路由。 Based on the value of my type value I create a new Object, like this: 基于我的type值的值,我创建一个新的对象,如下所示:

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". 即使我认为它仍然是“丑陋的” switch它也很快就失控了。 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; 编辑我使用的类与此use AppBundle\\Entity\\HardwareType;一起use AppBundle\\Entity\\HardwareType; etc. 等等

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 显然,您需要在文件的开头添加use ,并且可以在new类之前检查类是否存在。

Like this: 像这样:

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

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()! 然后只需检查键是否在数组中,如果是,则创建一个新的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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM