Welcome to the wonderful world of PHP variable scoping.
Functions and methods don't see any variables defined outside of them. You have to use the global
keyword to declare that you want access to variables defined outside of the function scope.
This won't work:
class Foo {
public function bar() {
echo $baz;
}
}
$f = new Foo();
$baz = 'Hello world!';
$f->bar(); // "Notice: Undefined variable: ..."
This will work:
class Foo2 {
public function bar() {
global $baz; // <- "I want $baz from the global scope"
echo $baz;
}
}
$f = new Foo2();
$baz = 'Hello world!';
$f->bar(); // "Hello world!"
Even though it works, you should avoid using it. There are better ways to go about passing in external object. One way is called "dependency injection", which is a fancy way of saying "pass in external dependencies during construction." For example:
class Index extends Application {
private $smarty;
public function __construct(Smarty $smarty) {
$this->smarty = $smarty;
}
public function showPage() {
$smarty->assign('foo', 'bar');
$smarty->display('index.tpl');
}
}
$sm = new Smarty(...);
$whatever = new Index($sm);
$whatever->showPage();
Another way is using a registry, which is a pattern used to store things that otherwise might be global variables. Let's try out Zend Registry as an example.
class Index extends Application {
public function showPage() {
$smarty = Zend_Registry::get('smarty');
$smarty->assign('foo', 'bar');
$smarty->display('index.tpl');
}
}
$sm = new Smarty(...);
Zend_Registry::set('smarty', $sm);
$whatever = new Index();
$whatever->showPage();