<?php
class BaseController extends Controller
{
protected $foo;
public function __construct()
{
$this->foo = '123';
}
protected function setupLayout()
{
if ( ! is_null($this->layout))
{
$this->layout = View::make($this->layout);
}
}
}
上面是BaseController
,我想将foo
声明为 123,但我可以在我从这个基本控制器扩展的控制器中获得foo
变量,你能帮忙吗?
public function detail($action)
{
return $this->foo;
}
根据文档:http://php.net/manual/en/language.oop5.decon.php
当你在父类构造函数中注意:如果子类,则不隐式调用父构造函数 定义构造函数。为了运行父构造函数,调用 父::__construct(( 在子构造函数中是必需的。
做一些工作时,你也必须直接在你的子类中调用它(即使这只是你在子构造函数中做的事情(。 即:
class ChildController extends BaseController
{
public function __construct() {
parent::__construct();
}
...
当您扩展控制器时,我想您当前正在执行以下操作:
<?php
class NewController extends BaseController
{
public function __construct()
{
// Do something here.
}
public function detail($action)
{
return $this->foo;
}
}
您会看到如何覆盖__construct
方法。您可以通过在方法的开头添加parent::__construct()
来轻松解决此问题,因此您将拥有以下内容:
<?php
class NewController extends BaseController
{
public function __construct()
{
parent::__construct();
// Do something here.
}
public function detail($action)
{
return $this->foo;
}
}