[英]Method chaining with variable variables
我正在使用的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();
$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();
如果沒有用戶輸入的風險 ,則可以創建所有對象鍵的字符串,並使用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在技術上是正確的( 在注釋中 ),我給出了實現。
因此,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
對象作為函數參數傳遞(如果我沒記錯的話,我認為這稱為依賴項注入),然后使用->
作為文字而不是駐留在變量內的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.