[Solved] Is there difference between echo “example” and “example” out of PHP tags? [duplicate]


For all pragmatic purposes, no, there is no relevant difference. Your script output will be “Example” in both cases. And in both cases, myCode() was executed before.

In fact, the OPCodes in both cases will be the same, because PHP will echo everything outside of <?php tags. It’s basically just an implicit echo.

Technically, the way to the resulting OPCodes will be different, but this has no relevant impact on performance. Mostly anything outside <?php tags is treated as T_INLINE_HTML by the parser. This is then converted to an echo in the abstract syntax tree:

|   T_INLINE_HTML { $$ = zend_ast_create(ZEND_AST_ECHO, $1); }

with ZEND_AST_ECHO being

case ZEND_AST_ECHO:
APPEND_NODE_1("echo");

However, your aim should be to separate logic from your views and templates as good as possible as it can easily lead to spaghetti code if you don’t. As a rule of thumb, a function should not echo, but return strings. Most frameworks only echo once: at the end of a request when rendering the response.

Since you mentioned “Views” and MVC: a View in MVC is not necessarily a template, but a specific representation of a particular piece of data from the Model. It can be code that ultimately renders a template though. If that’s what you want, you probably want to check out a template engine, like Twig (although PHP is a template engine on it’s own).

4

solved Is there difference between echo “example” and “example” out of PHP tags? [duplicate]