__toString magic and type coercion

tairmUniornom

New Member
I've created a \[code\]Template\[/code\] class for managing views and their associated data. It implements \[code\]Iterator\[/code\] and \[code\]ArrayAccess\[/code\], and permits "sub-templates" for easy usage like so:\[code\]<p><?php echo $template['foo']; ?></p><?php foreach($template->post as $post): ?> <p><?php echo $post['bar']; ?></p><?php endforeach; ?>\[/code\]Anyways, rather than using inline core functions, such as \[code\]hash()\[/code\] or \[code\]date()\[/code\], I figured it would be useful to create a class called \[code\]TemplateData\[/code\], which would act as a wrapper for any data stored in the templates.This way, I can add a list of common methods for formatting, for example:\[code\]echo $template['foo']->asCase('upper');echo $template['bar']->asDate('H:i:s');//etc..\[/code\]When a value is set via \[code\]$template['foo'] = 'bar';\[/code\] in the controllers, the value of \[code\]'bar'\[/code\] is stored in it's own \[code\]TemplateData\[/code\] object.I've used the magic \[code\]__toString()\[/code\] so when you echo a \[code\]TemplateData\[/code\] object, it casts to \[code\](string)\[/code\] and dumps it's value. However, despite the mantra controllers and views should not modify data, whenever I do something like this:\[code\]$template['foo'] = 1;echo $template['foo'] + 1; //exception\[/code\]It dies on a \[code\]Object of class TemplateData could not be converted to int\[/code\]; Unless I recast \[code\]$template['foo']\[/code\] to a string:\[code\]echo ((string) $template['foo']) + 1; //outputs 2\[/code\]Sort of defeats the purpose having to jump through that hoop. Are there any workarounds for this sort of behavior that exist, or should I just take this as it is, an incidental prevention of data modification in views?
 
Top