php - __toString magic and type coercion -
i've created template
class managing views , associated data. implements iterator
, arrayaccess
, , permits "sub-templates" easy usage so:
<p><?php echo $template['foo']; ?></p> <?php foreach($template->post $post): ?> <p><?php echo $post['bar']; ?></p> <?php endforeach; ?>
anyways, rather using inline core functions, such hash()
or date()
, figured useful create class called templatedata
, act wrapper data stored in templates.
this way, can add list of common methods formatting, example:
echo $template['foo']->ascase('upper'); echo $template['bar']->asdate('h:i:s'); //etc..
when value set via $template['foo'] = 'bar';
in controllers, value of 'bar'
stored in it's own templatedata
object.
i've used magic __tostring()
when echo templatedata
object, casts (string)
, dumps it's value. however, despite mantra controllers , views should not modify data, whenever this:
$template['foo'] = 1; echo $template['foo'] + 1; //exception
it dies on object of class templatedata not converted int
; unless recast $template['foo']
string:
echo ((string) $template['foo']) + 1; //outputs 2
sort of defeats purpose having jump through hoop. are there workarounds sort of behavior exist, or should take is, incidental prevention of data modification in views?
echo attempting echo results of $template['foo'] + 1
. since $template['foo']
object of type templatedata
, 1
int
, you're receiving error. in case, ((string) $template['foo'])
not "recasting", casting first time.
Comments
Post a Comment