这是昨天范围问题的后续跟进。
stackoverflow.com/questions/3301377/class-scope-question-in-php
今天我想与子类共享“$ template_instance”变量。 这是如何完成的?
require_once("/classes/Conf.php");
require_once("/classes/Application.php");
class index extends Application
{
private $template_instance;
// Dependency injection
public function __construct(Smarty $template_instance)
{
$this->template_instance = $template_instance;
}
function ShowPage()
{
// now let us try to move this to another class
// $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();
$printpage_instance = new printpage();
$printpage_instance->printSomething();
------------------------------------------------------------------
class printpage
{
public function __construct()
{
}
public function printSomething()
{
// now let us try to move this to another class
$this->template_instance->assign('name', 'Ned');
$this->template_instance->display('index.tpl');
}
}
答案 0 :(得分:1)
制作protected。受保护的成员只能访问该类及其子级。
答案 1 :(得分:0)
与之前被告知的方式完全相同
$printpage_instance = new printpage($template_instance);
$printpage_instance->printSomething();
------------------------------------------------------------------
class printpage
{
private $template_instance;
public function __construct(Smarty $template_instance)
{
$this->template_instance = $template_instance;
}
public function printSomething()
{
// now let us try to move this to another class
$this->template_instance->assign('name', 'Ned');
$this->template_instance->display('index.tpl');
}
}
或将索引传递给printpage构造函数
$printpage_instance = new printpage($template_instance);
$printpage_instance->printSomething();
------------------------------------------------------------------
class printpage
{
private $index;
public function __construct(index $index)
{
$this->index = $index;
}
public function printSomething()
{
$this->index->ShowPage();
}
}