PHP类中的范围问题:
为什么这样做?
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 =新索引; $ index_instance-> SHOWPAGE();
但这不起作用?
class index extends Application
{
function ShowPage()
{
$smarty->assign('name', 'Ned');
$smarty->display('index.tpl');
}
}
$index_instance = new index;
$smarty = new Smarty();
$index_instance->ShowPage();
答案 0 :(得分:3)
欢迎来到PHP变量范围的精彩世界。
函数和方法看不到在它们之外定义的任何变量。您必须使用global
关键字来声明您希望访问在函数范围之外定义的变量。
这不起作用:
class Foo {
public function bar() {
echo $baz;
}
}
$f = new Foo();
$baz = 'Hello world!';
$f->bar(); // "Notice: Undefined variable: ..."
此将工作:
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!"
尽管它有效,但您应该避免使用它。有更好的方法可以传递外部对象。一种方法称为“dependency injection”,这是一种说“在构造期间传递外部依赖关系”的奇特方式。例如:
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();
另一种方法是使用注册表,这是一种用于存储可能是全局变量的东西的模式。我们试试Zend Registry作为例子。
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();
答案 1 :(得分:1)
简单:因为$ smarty在$ index_instance范围内不存在。
如果你想在索引类之外实例化一个新的Smarty,那么你需要将smarty传递给索引实例:
class index extends Application
{
private $smarty = null;
function __construct($smarty) {
$this->smarty = $smarty;
}
function ShowPage()
{
$this->smarty->assign('name', 'Ned');
$this->smarty->display('index.tpl');
}
}
$smarty = new Smarty();
$index_instance = new index($smarty);
$index_instance->ShowPage();
答案 2 :(得分:0)
我现在正在使用依赖注入方法。
require_once("/classes/Conf.php");
require_once("/classes/Application.php");
class index extends Application
{
private $template_instance;
public function __construct(Smarty $template_instance)
{
$this->template_instance = $template_instance;
}
function ShowPage()
{
$this->template_instance->assign('name', 'Ned');
$this->template_instance->display('index.tpl');
}
}
$template_instance = new Smarty();
$index_instance = new Index($template_instance);
$index_instance->showPage();