阔别了几个月,小杨又来分享php知识。话不多说,言归正传,今天继续带来smarty的知识点。
-----------------smarty assign append 详解
对于这两个的区别和联系需要分析smarty的源码-smarty.Class.php
public function assign($tpl_var, $value = null, $nocache = false)
{
if (is_array($tpl_var)) {
foreach ($tpl_var as $_key => $_val) {
$this->assign($_key, $_val, $nocache);
}
} else {
if ($tpl_var != '') {
if ($this->_objType == 2) {
$this->_assignInScope($tpl_var, $value, $nocache);
} else {
$this->tpl_vars[ $tpl_var ] = new Smarty_Variable($value, $nocache);
}
}
}
return $this;
}
/*
通过源码的分析得到:如果只传入一个数组,那么数组会循环赋值,等同于 $smarty->assign('lang','php')$smarty->assign('like','yes')
*/
public function append(Smarty_Internal_Data $data, $tpl_var, $value = null, $merge = false, $nocache = false)
{
if (is_array($tpl_var)) {
// $tpl_var is an array, ignore $value
foreach ($tpl_var as $_key => $_val) {
if ($_key != '') {
$this->append($data, $_key, $_val, $merge, $nocache);
}
}
} else {
if ($tpl_var != '' && isset($value)) {
if (!isset($data->tpl_vars[ $tpl_var ])) {
$tpl_var_inst = $data->ext->getTemplateVars->_getVariable($data, $tpl_var, null, true, false);
if ($tpl_var_inst instanceof Smarty_Undefined_Variable) {
$data->tpl_vars[ $tpl_var ] = new Smarty_Variable(null, $nocache);
} else {
$data->tpl_vars[ $tpl_var ] = clone $tpl_var_inst;
}
}
if (!(is_array($data->tpl_vars[ $tpl_var ]->value) ||
$data->tpl_vars[ $tpl_var ]->value instanceof ArrayAccess)
) {
settype($data->tpl_vars[ $tpl_var ]->value, 'array');
}
if ($merge && is_array($value)) {
foreach ($value as $_mkey => $_mval) {
$data->tpl_vars[ $tpl_var ]->value[ $_mkey ] = $_mval;
}
} else {
$data->tpl_vars[ $tpl_var ]->value[] = $value;
}
}
if ($data->_objType == 2 && $data->scope) {
$data->ext->_updateScope->_updateScope($data, $tpl_var);
}
}
return $data;
}
/*
分析得到:当参数一相同的时候,会产生覆盖,后一个覆盖前一个 解决知道 append 追加
*/
$smarty->append('teacher','冯老师');
$smarty->append('teacher','曾老师');
$smarty->append('teacher','许老师');
/*
分析源码:可以得出:如果 参数一相同 那么 会组建一个数组(
$this->tpl_val['teacher'][] = '冯老师' $this->tpl_val['teacher'][] = '曾老师' $this->tpl_val['teacher'][] = '许老师'
)
*/