2013-12-18 4 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

클래스의 보호와 $ 뷰를 정의하고이 코드 때문에하지 않도록 당신은 종속성을 incentlye

,
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; 
    } 
} 
관련 문제