__toString magic and type of coercion

I created a class for managing views and related data. It implements and enables "subpatterns" for easy use as follows: TemplateIteratorArrayAccess

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

In any case, instead of using the built-in basic functions, such as hash()or date(), I decided that it would be useful to create a class with a name that would act as a wrapper for any data stored in the templates. TemplateData

Thus, I can add a list of common formatting methods, for example:

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

When a value is set through $template['foo'] = 'bar';in the controllers, the value is 'bar'stored in its own TemplateDataobject.

__toString(), , - TemplateData, (string) . , , , , - :

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

Object of class TemplateData could not be converted to int; $template['foo'] :

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

, . - , , , ?

+3
3

, , ; __invoke() TemplateData, $_data, . :

//in controller
$template['foo'] = 'bar';
$template['abc'] = 123;

//in view
echo $template['foo']();                       //bar
echo $template['foo']->asHash('md5');          //37b51d194a7513...
echo $template['abc']();                       //123
echo $template['abc']() + 123;                 //246
echo $template['abc']->asHash('md5');          //202cb962ac5907...

//__invoke also takes $function and $arguments for alternative syntax
echo $template['foo']('asHash', array('md5')); //37b51d194a7513...

, , , - :

echo $template['foo']->asHash('md5')->asCase('upper');

. " " - , , . ( ) __invoke() :

echo $template['foo'](
    array('asHash', 'asCase'),          //ordered array of method names
    array(array('md5'), array('upper')) //ordered array of method argument arrays
);

- ?

0

$template['foo'] + 1. $template['foo'] TemplateData, 1 int, . ((string) $template['foo']) "", .

+1

PHP does not support operator loading . If you want to be able to do the addition (or anything else related to operators, for that matter), you will need to provide a method for each operator that you want to support. Most likely, its implementation in the base class template will be sufficient for ordinary cases, which will allow you to extend it later if necessary. Although use (string)in your object is a shortcut, I would advise it.

+1
source

Source: https://habr.com/ru/post/1796157/


All Articles