__toString magic and type coercion

Posted by TomcatExodus on Stack Overflow See other posts from Stack Overflow or by TomcatExodus
Published on 2011-03-03T22:23:35Z Indexed on 2011/03/03 23:25 UTC
Read the original article Hit count: 252

I've created a Template class for managing views and their associated data. It implements Iterator and ArrayAccess, and permits "sub-templates" for easy usage like so:

<p><?php echo $template['foo']; ?></p>
<?php foreach($template->post as $post): ?>
    <p><?php echo $post['bar']; ?></p>
<?php endforeach; ?>

Anyways, rather than using inline core functions, such as hash() or date(), I figured it would be useful to create a class called TemplateData, 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:

echo $template['foo']->asCase('upper');
echo $template['bar']->asDate('H:i:s');
//etc..

When a value is set via $template['foo'] = 'bar'; in the controllers, the value of 'bar' is stored in it's own TemplateData object.

I've used the magic __toString() so when you echo a TemplateData object, it casts to (string) and dumps it's value. However, despite the mantra controllers and views should not modify data, whenever I do something like this:

$template['foo'] = 1;
echo $template['foo'] + 1; //exception

It dies on a Object of class TemplateData could not be converted to int; Unless I recast $template['foo'] to a string:

echo ((string) $template['foo']) + 1; //outputs 2

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?

© Stack Overflow or respective owner

Related posts about php

Related posts about type-conversion