我有以下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