6

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

Ariyan
  • 14,760
  • 31
  • 112
  • 175
  • 1
    You need to assign the variable to the smarty object or smarty won't be able to access it. There's no magic wand to get around this. –  Jan 27 '12 at 15:04

3 Answers3

11

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
Darin Peterson
  • 1,262
  • 2
  • 15
  • 25
7

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
AndrewPK
  • 6,100
  • 3
  • 32
  • 36
4

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

$smarty->assign('foo', $foo);
JochenJung
  • 7,183
  • 12
  • 64
  • 113