2016-12-25 1 views
1

다른 클래스의 하위 클래스 인 상위 클래스에있는 데이터에 액세스하여 수정하려고합니다. 내가 부모 클래스를했습니다PHP의 다중 레벨 상속

class GrandParent { 
    protected $data = 1; 

    public function __construct() {} 

    public function getData() { 
     return $this->data; 
    } 
} 

나는 Child 클래스를 인스턴스화하려고 getData()을, 내가 정상이 얻을 경우 아래 내 첫 번째 수준 하위

class Child extends GrandParent { 
    protected $c1Data; 

    public function __construct() { 
     $this->c1Data = parent::getData(); 
     $this->c1Data = 2; 
    } 

    public function getData() { 
     return $this->c1Data; 
    } 
} 

입니다. 나는 다른 클래스를 상속받은 Child 있습니다.

class GrandChild extends Child { 
    protected $c2Data; 

    public function __construct() { 
     $this->c2Data = parent::getData(); 
    } 

    public function getData() { 
     return $this->c2Data; 
    } 
} 

문제는 그 내가 GrandChild I를 인스턴스화하고 내가 null 받고 있어요 데이터를 얻을하려고합니다. 내 GrandChild 클래스가 $c1Data = 2을 상속 받고 작업 할 수 있습니까? 또한 ChildGrandParent 클래스를 자체적으로 사용할 수 있고 추상적이 아니길 원합니다.

답변

2

Child 클래스의 __constructor가 호출되지 않기 때문에 당신은 NULL을 얻고 및 c1Data 속성 을 설정하지 않은 이유입니다. 명시 적으로 Child__constructor을 요구한다 : 지금 작동 @u_mulder

class GrandChild extends Child { 
    protected $c2Data; 

    public function __construct() { 
     // here 
     parent::__construct(); 

     $this->c2Data = parent::getData(); 
    } 

    public function getData() { 
     return $this->c2Data; 
    } 
} 
+0

감사합니다. 멍청한 실수. – Lexx