{php} does not get access to $this
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:
- Introduce a new variable (such as
$smarty,$tplor$template) or document$_smarty_tplinstead of$this. Both are not backwards-compatible, but introduce no run-time cost. - Call the generated
content_…functions with$thisbound to$_smarty_tplusingClosure::call(PHP 7.0+) orClosure::bindTo(PHP 5.4+); unfortunately I can't seem to find a solution for 5.3. This gives a performance penalty. - 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?).
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?
@mohrt could you change $this in Example 7.62 on https://www.smarty.net/docs/en/language.function.php.tpl to $_smarty_tpl?
fixed