从扩展类访问属性

时间:2015-03-23 07:39:28

标签: php

<?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;
}

2 个答案:

答案 0 :(得分:0)

按照文档: http://php.net/manual/en/language.oop5.decon.php

  

注意:如果子类,则不会隐式调用父构造函数   定义构造函数。为了运行父构造函数,调用   子构造函数中的parent :: __ construct()是必需的。

当你在父类构造函数中做一些工作时,你必须直接在你的子类中调用它(即使这只是你在子构造函数中做的事情)。即:

class ChildController extends BaseController
{
    public function __construct() {
        parent::__construct();
    }

...

答案 1 :(得分:-1)

当你扩展控制器时,我想你现在正在这样做:

<?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;
    }
}
相关问题