我应该如何访问此变量?
class BaseController
{
public function __construct()
{
$view = new Views;
$view->layout = 'master';
}
}
所以我想在我的其他控制器上访问$ view
class HomeController extends BaseController
{
public function showForm()
{
// Access $view
}
}
答案 0 :(得分:2)
这种方式你不能。 $view
是函数中的局部变量。但你可以把它设为protected
property,因此无法从外部访问,但可以继承:
声明受保护的成员只能在类中访问 本身以及继承和父类。
所以你的课程就像:
class BaseController
{
protected $view;
public function __construct()
{
$this->view = new Views;
$this->view->layout = 'master';
}
}
然后访问它:
class HomeController extends BaseController
{
public function showForm()
{
echo $this->view->layout;
}
}
答案 1 :(得分:1)
class BaseController {
protected $view = null;
public function __construct() {
$view = new Views;
$view->layout = 'master';
$this->view = $view;
}
}
class HomeController extends BaseController {
public function showForm() {
// Access $view
echo parent::$view;
}
}
答案 2 :(得分:1)
class BaseController
{
public function __construct()
{
$this->view = new Views;
$this->view->layout = 'master';
}
}
class HomeController extends BaseController
{
public function showForm()
{
echo $this->view->layout;
}
}
答案 3 :(得分:1)
使用protected in class定义$ view并避免使用此代码,因为您增加了依赖性
class BaseController{
public function __construct(){
$view = new Views;
$view->layout = 'master';
}
}
将您的代码更改为:
class BaseController{
protected $view;
public function __construct($view = null){
$this->view = $view;
$this->view->layout = 'master';
}
}
class HomeController extends BaseController{
public function showForm(){
echo parent::$view;
}
}