Accessing a variable (local or global) of PHP file from smarty

匿名 (未验证) 提交于 2019-12-03 03:03:02

问题:

I have a php file that has some local and global variables (e.g. $foo)
an smarty object is called from this file.
How can I access $foo from smarty script without changing PHP file?

Thanks

回答1:

You can't. You have to assign it to smarty within the PHP file.

$smarty->assign('foo', $foo); 


回答2:

If you have a constant variable called BASE, and defined like this:

define('BASE', 'Boise'); 

you can access the variable in smarty the following way:

$smarty.const.BASE 


回答3:

You used to be able to get around this by using {php}{/php} tags, but since this is deprecated, now you have to assign your variables via $smarty->assign(), the only exception to this is constants and server variables which you still have direct access to via the $smarty object.

(You can also re-enable the {php} tags if you'd like and don't care about the potential security reasons they were disabled for in the first place).

Any of the request variables such as $_GET, $_POST, $_COOKIE, $_SERVER, $_ENV and $_SESSION are available via the $smarty object.

Due to this - most of the data I work with can simply be accessed via the $smarty object without having to create a ton of (copied) variables.

eg.:

  • Accessing a constant: {$smarty.const.MY_CONST_VAL}
  • Accessing a $_SERVER var: {$smarty.server.REQUEST_METHOD} //Everything in $_SERVER is accessible
  • Grabbing something from $_SESSION: {$smarty.session.MY_SESSION_VAL} //Everything in $_SESSION is available


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!