Accessing a variable (local or global) of PHP file

2019-03-29 23:01发布

问题:

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