2012-08-15 28 views
1

我有以下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中完成这一行在一行发言而不是两个。我认为必须有一种特殊的方式来做到这一点。

+1

用一样['sprintf的()'](http://us.php.net/manual/en/function.sprintf.php)? 'sprintf(“Select%s now!”,$ cfg ['methodValue'])' – 2012-08-15 15:56:34

回答

6

首先,简化了那场可怕的代码如下:

public function createOptions($options, array $cfg = array()) { 
    $cfg += array(
     'methodKey' => 'getId', 
     'methodValue' => 'getName', 
     ... 
    ); 

无需所有isset和重复键名,一个简单的数组工会就行了。

其次,你可以使用类似sprintf

$cfg['surroundingValue'] = 'Select %s now!'; 
echo sprintf($cfg['surroundingValue'], $valueInTheMiddle); 
+0

这段代码是做什么的$ cfg + = array('? – Jocelyn 2012-08-15 16:04:47

+0

Array union:http://www.php.net/ manual/en/language.operators.array.php – deceze 2012-08-15 16:05:54

+0

我之前使用过数组合并,但是我从来没有想过在这样的地方使用它,所以谢谢你的支持, 纠正我,如果我错了,但是$ cfg + = array(// defaultconditions)与$ cfg = $ cfg + array(// defaultconditions)是一样的array_merge($ cfg,array(// defaultconditions) 基本上如果key存在在$ cfg中,这将是所得到的$ cfg变量中使用的值,否则将使用默认值 – Justin 2012-08-15 16:09:15

相关问题