scope issue in PHP classes:
Why does this work?
class index extends Application
{
function ShowPage()
{
$smarty = new Smarty(); // construct class
$smarty->assign('name', 'Ned'); // then call a method of class
$smarty->display('index.tpl');
}
}
$index_instance = new index;
$index_instance->ShowPage();
but this does not work?
class index extends Application
{
function ShowPage()
{
$smarty->assign('name', 'Ned');
$smarty->display('index.tpl');
}
}
$index_instance = new index;
$smarty = new Smarty();
$index_instance->ShowPage();
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
globalkeyword to declare that you want access to variables defined outside of the function scope.This won’t work:
This will work:
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:
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.