2012-03-25 3 views
2

자신의 바르를로드 할 부모가 없을 수 있습니다 :PHP는 나는이처럼 보이는 핸들러 클래스가

class Handler{ 
    public $group; 

    public function __construct(){ 
     $this->group = $this->database->mysql_fetch_data("blabla query"); 
     //if i print_r($this->group) here it gives proper result 

     new ChildClass(); 
    } 

    public function userGroup(){ 
     print_r($this->group); //this is empty 
        return $this->group; 
    } 
} 

class ChildClass extends Handler{ 

    public function __construct(){ 
     $this->userGroup(); 
     //i tried this too 
     parent::userGroup(); 
     //userGroup from parent always returns empty 
    } 

} 

워크 플로우 :

  • 핸들러 내 index.php를과에서 호출 __construct이

  • 핸들러라고하는 것은 $ 그룹을 만들 필요가

  • 처리기 내가

아이 대신 처리기에서 $ this-> 그룹을 얻을 그것은 시도하는 함수에서 $ 그룹을 반환 할 때 자식 클래스는 핸들러 함수

  • 를 호출

  • 자식 클래스를 생성

    부모에게 물어볼 때마다 상위 함수에만 액세스 할 수 있고 부모 클래스는 자체 변수를 찾을 수 없습니다.

    EDIT :

    'extends'를 사용하여 부모 함수를 호출하는 것이 유용 할 것이라고 생각했지만, $ this를 자식에게 전달하는 것이 더 쉬울 것 같습니다.

  • 답변

    2

    부모 개체를 호출 한 적이 없으므로 그룹 개체가 초기화되지 않습니다. 이런 식으로하고 싶을 것입니다.

    class Handler{ 
        public $group; 
    
        public function __construct(){ 
         $this->group = $this->database->mysql_fetch_data("blabla query"); 
         //if i print_r($this->group) here it gives proper result 
    
         new ChildClass(); 
        } 
    
        public function userGroup(){ 
         print_r($this->group); //this is empty 
            return $this->group; 
        } 
    } 
    
    class ChildClass extends Handler{ 
    
        public function __construct(){ 
         parent::__construct(); 
         $this->userGroup(); 
        } 
    
    } 
    

    는 당신이 하지이 확장 된 클래스에서 __construct 방법을 덮어 쓰기 한 경우, 부모 __construct가 자동으로 호출되었을 것입니다,하지만 당신은 확장 한 클래스에서이를 덮어 때문에, 당신은 부모의 전화를 말해야한다 확장 클래스의 __construct __construct.

    +0

    또는 그는'public $ group'이 정적이고 실제로 두 개의 다른 객체를 갖고 싶지 않을 수도 있습니다. : p – Basti

    +0

    @Basti 어느 쪽이든, 그는 위와 같은 조치를 취해야합니다. 그리고 그가 당신이 말하는 것을 언급하지 않았기 때문에, 왜 당신이 그것을 가져올 지 확신하지 못합니다. – dqhendricks

    +0

    부모가 자식을 다시 호출하면 무한 루프가 발생합니다. – MakuraYami

    관련 문제