RE: [SMARTY] Assign a reference to a variable

From: Date: Fri, 02 Aug 2002 07:48:11 +0000
Subject: RE: [SMARTY] Assign a reference to a variable
Groups: php.smarty.general 
Request: Send a blank email to php-smarty-general+get-5548@lists.php.net to get a copy of this message
On 2 Aug 2002 at 9:23, Rasmus T. Mohr wrote: > Is it a problem? In the first example you are passing a copy of $myobj to > the templates and then modifying the attributes of the original object (not > the one passed to the templates). In the second example you are passing by > reference, so further changes will affect the object known to the templates. > > This is intended behavior... No, that's not true :-) Lets have a look at the assign() method: function assign($tpl_var, $value = NULL) { if (is_array($tpl_var)){ foreach ($tpl_var as $key => $val) { if (!empty($key) && isset($val)) { $this->_tpl_vars[$key] = $val; } } In my experience, foreach() does not allow references so if $value is something like array('key' => &$value), $val will be a *copy*, not a reference. } else { if (!empty($tpl_var) && isset($value)) $this->_tpl_vars[$tpl_var] = $value; Here is the problem again: $value is not saved by reference in the $this->_tpl_vars array, but by copying it. So if assign() is called by reference: assign('name', &$value), the reference won't be applied to the $_tpl_vars array. To remove the problem, write &$value here. } $this->_extract = true; } You see: It does not matter if you pass values by reference to the assign() method. I want to suggest to replace the apply() method in CVS with this one - it does not have any disadvantages as it is backward compatible with arguments passed by copy. I've marked comments green and changes red if your mailer supports rich text. function assign($tpl_var, $value = NULL) { if (is_array($tpl_var)){ foreach ($tpl_var as $key => $val) { // foreach() doesn't support references $val = &$tpl_var[$key]; if (!empty($key) && isset($val)) { // keep references $this->_tpl_vars[$key] = &$val; } // free references unset($val); } } else { if (!empty($tpl_var) && isset($value)) // keep references $this->_tpl_vars[$tpl_var] = &$value; } $this->_extract = true; } -- Ferdinand Beyer <fbeyer@clickhand.de>

« previous php.smarty.general (#5548) next »