如何在foreach循环中使用对象并替换变量(OOP)?

时间:2018-11-19 19:04:07

标签: php loops oop object

此代码...

 foreach ($classes->fieldMappings as $fieldMapping) {
        echo $fieldMapping['fieldName'];
 }

...给我以下输出:

id
username
password
email
isActive

我现在想做的是,我想放这段代码...

$entity->setUsername($data['form[username]']);
$entity->setEmail($data['form[email]']);
$entity->setPassword($data['form[password]']);
$entity->setIsActive($data['form[isActive]']);

...进入循环。所以我这样替换它:

foreach ($classes->fieldMappings as $fieldMapping) { 
   $entity->set'.$fieldMapping['fieldName'].'($data['form['.$fieldMapping['fieldName'].']']);
}

我遇到了解析错误,但实际上我不知道如何以正确的方式编写此错误。

2 个答案:

答案 0 :(得分:4)

您可以在一行中完成此操作,请参见PHP: Strings上的复杂(卷曲)语法

$entity->{'set'.$fieldMapping['fieldName']}($data['form['.$fieldMapping['fieldName'].']']);

不过,它可能更具可读性:

$func = 'set'.$fieldMapping['fieldName'];
$args = $data['form['.$fieldMapping['fieldName'].']'];
$entity->$func($args);

答案 1 :(得分:1)

尝试将您的方法名称包装在花括号中,使其类似:

 $entity->{'set'.$fieldMapping['fieldName']}(...)