我有以下PHP函數:用PHP中的其他文本包圍字符串的一些方法?
public function createOptions($options, $cfg=array()) {
$cfg['methodKey'] = isset($cfg['methodKey']) ? $cfg['methodKey'] : 'getId';
$cfg['methodValue'] = isset($cfg['methodValue']) ? $cfg['methodValue'] : 'getName';
$cfg['beforeKey'] = isset($cfg['beforeKey']) ? $cfg['beforeKey'] : '';
$cfg['beforeValue'] = isset($cfg['beforeValue']) ? $cfg['beforeValue'] : '';
$cfg['afterKey'] = isset($cfg['afterKey']) ? $cfg['afterKey'] : '';
$cfg['afterValue'] = isset($cfg['afterValue']) ? $cfg['afterValue'] : '';
$array = array();
foreach ($options as $obj) {
$array[$cfg['beforeKey'] . $obj->$cfg['methodKey']() . $cfg['afterKey']] = $cfg['beforeValue'] . $obj->$cfg['methodValue']() . $cfg['afterValue'];
}
return $array;
}
這件事情,我用在我的應用程序來創建數組數據選擇框。我最近添加了4個新的$ cfg變量,用於在選擇框的鍵和值之前或之後添加字符串。因此,舉例來說,如果我的下拉列表看起來像「A,B,C」在默認情況下,我可以通過:
$cfg['beforeValue'] = 'Select ';
$cfg['afterValue'] = ' now!';
,並得到「選擇現在!選擇B現在!選擇C吧!」
所以這工作得很好,但我想知道是否有某種方式在PHP中完成這一行在一行發言而不是兩個。我認爲必須有一種特殊的方式來做到這一點。
用一樣['sprintf的()'](http://us.php.net/manual/en/function.sprintf.php)? 'sprintf(「Select%s now!」,$ cfg ['methodValue'])' – 2012-08-15 15:56:34