2013-12-18 182 views
2

我應該如何訪問這個變量?訪問父變量

class BaseController 
{ 
    public function __construct() 
    { 
     $view = new Views; 
     $view->layout = 'master'; 
    } 
} 

所以我想我的其他控制器

class HomeController extends BaseController 
{ 
    public function showForm() 
    { 
     // Access $view 
    } 
} 

回答

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

定義$視圖在課堂上的保護,避免這個代碼,因爲你增加了依賴關係

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