用可变变量链接的方法

问题描述 投票:0回答:2

我正在使用的API(Oracle Service Cloud的ConnectPHP)遵循链接方法。例如:

$incident = new Incident();
$incident->CustomFields->c->make = "Same value";
$incident->StatusWithType->Status->ID = 34;
$incident->save();

如果动态生成$incident对象的后续属性,我将如何实现相同的目标?例如:

$data = array();
$data[0]['parts'] = array('CustomFields', 'c', 'make');
$data[0]['value'] = "Some value";

$data[1]['parts'] = array('StatusWithType', 'Status', 'ID');
$data[1]['value'] = 34;

$incident = new Incident();
foreach($data as $array)
{
   foreach($array['parts'] as $key)
   {  
      // how will I generate 
      // (1) $incident->CustomFields->c->make = $array['value']
      // (2) $incident->StatusWithType->Status->ID = $array['value']
   }
}
$incident->save();

What I tried

$incident = new Incident();
foreach($data as $array)
{
   $parts = implode('->', $array['parts']);
   $incident->{$parts} = $array['value']; // this doesn't work even though $parts is coming out with the expected pattern because I think it is converting it into a string representation
}
$incident->save();
php oop rightnow-crm oracle-service-cloud
2个回答
1
投票

如果没有用户输入的风险,您可以创建所有对象键的字符串并像这样使用eval

$incident = new stdClass();
foreach($data as $key=>$chain){
  $str = "{'".implode("'}->{'",$chain['parts'])."'}";
  eval("@\$incident->$str = '$chain[value]';");
}
print_r($incident);

现场演示:https://eval.in/923232

输出为

stdClass Object
(
    [CustomFields] => stdClass Object
        (
            [c] => stdClass Object
                (
                    [make] => Some value
                )

        )

    [StatusWithType] => stdClass Object
        (
            [Status] => stdClass Object
                (
                    [ID] => 34
                )

        )

)

现在你可以轻松访问像$incident->CustomFields->c->make

@kranthi在技术上是正确的(在评论中),我给出了实现。


0
投票

所以,kranthi走在了正确的轨道上。

$incident = new Incident();
foreach($data as $array)
{
   $this->setDynamicFields($incident, $array['parts'], $array['value']); 
}
$incident->save();

function setDynamicFields($obj, $parts, $value)
{
   if(is_array($parts) && count($parts) == 3)
   {
       $obj->{$parts[0]}->{$parts[1]}->{$parts[2]} = ($parts[0] == 'StatusWithType' ? (int) $value: $value);
   }
}

诀窍是将整个$incident对象作为函数参数传递(我认为如果我没有错,则称为依赖注入)并使用->作为文字而不是驻留在变量中的字符串。

© www.soinside.com 2019 - 2024. All rights reserved.