smarty icon indicating copy to clipboard operation
smarty copied to clipboard

{php} does not get access to $this

Open luzat opened this issue 8 years ago • 2 comments

When using SmartyBC and {php} support it seems that code such as the following should work:

{php}
$this->assign('someVar', 123);
{/php}

Unfortunately, when templates are compiled, $this does not seem to be accessible (PHP 7.1+: "Fatal error: Uncaught Error: Using $this when not in object context"; but the lack of context should give problems in older PHP versions, too). A workaround is:

{php}
$_smarty_tpl->assign('someVar', 123);
{/php}

There are a couple of possible simple fixes which Smarty could implement:

  1. Introduce a new variable (such as $smarty, $tpl or $template) or document $_smarty_tpl instead of $this. Both are not backwards-compatible, but introduce no run-time cost.
  2. Call the generated content_… functions with $this bound to $_smarty_tpl using Closure::call (PHP 7.0+) or Closure::bindTo (PHP 5.4+); unfortunately I can't seem to find a solution for 5.3. This gives a performance penalty.
  3. Instead of binding the whole function body to $this, just use it for each {php}…{/php} part.

The third option is my favorite. It makes the invocation of (hopefully seldom used) {php} blocks slightly slower, does not introduce additional costs and works with PHP 5.4+ using Closure::bindTo. A change in behavior this brings would be that {php} blocks following each other would not be able to share PHP variables because they use a different function context (but this was probably undocumented behavior anyway?).

luzat avatar Feb 24 '18 17:02 luzat

Seeing that this is all very deprecated and discouraged, I'm in favor of fixing the docs to reflect the way it works now. @mohrt could you change $this in Example 7.62 on https://www.smarty.net/docs/en/language.function.php.tpl to $_smarty_tpl?

wisskid avatar Feb 19 '20 22:02 wisskid

@mohrt could you change $this in Example 7.62 on https://www.smarty.net/docs/en/language.function.php.tpl to $_smarty_tpl?

wisskid avatar Sep 14 '22 09:09 wisskid

fixed

mohrt avatar Aug 07 '23 00:08 mohrt