Re: RFC: Short echo tag can also call closures
| From: | Lanre Waju | Date: | Mon, 18 Sep 2023 19:07:52 +0000 |
| Subject: | Re: RFC: Short echo tag can also call closures | ||
| References: | 1 2 3 4 | Groups: | php.internals |
| Request: | Send a blank email to internals+get-121095@lists.php.net to get a copy of this message | ||
I think a big part of your problem is misusing PHP constructs. Why are you adding a function as a property? Of course the engine sees it as a method call, you can't even use a callable as the typehint for a property. If the 'body' function is separate from each instance, why not make it a static method in the class?
Lanre
On 2023-09-18 1:03 p.m., Shailesh Humbad wrote:
On 9/18/2023 2:40 PM, Dusk wrote:Surely this can already be accomplished unambiguously using syntax likeBoth of the examples do not work because in the use case, the model property can interchangeably be either a string or a closure depending on the size of the content. It won't always be a closure. For example, the controller logic could be written as either: $model->body = "Hello world"; or $model->body = function() { readfile("helloworld.txt"); }; This change would break compatibility with code written like "<?= $x ?>", where $x is an object that implements both __invoke and __toString. I would suspect that such code is extremely rare or non-existent. Just FYI, if $model->body is a closure, then this code does not work: <?= $model->body(); ?> PHP tries to call the class method named 'body', which is undefined. However, your example does work: <?= ($model->body)(); ?> In any case, my workaround is this: <?php is_callable($model->body) ? call_user_func($model->body) : echo $model->body; ?> It would just be nice to be able to write the view without any spaghetti code, as simply: <?= $model->body ?> Regards, Shailesh<?= $x() ?>or<? ($model->title)() ?>? In any case, this seems like a non-starter, as it would substantially change the behavior of some existing code, e.g. when echoing objects which implement both __invoke() and __toString().