2017-04-24 1 views
0

둘 다 추상 클래스를 확장하는 2 개의 클래스가 있습니다. 두 클래스에는 "content"라는 private 메서드가 있습니다.이 메서드는 다른 클래스의 항목 배열입니다. 내가 클래스 AI의 "내용"배열로 객체 B를 추가 항목 객체 B. 다음 에서 부모 객체 A를 얻을 필요가 예되면 은, 그것을보고 쉽게 :개체 배열에서 상위 수준 개체 가져 오기 항목

<?php 
 

 
abstract class heroes { 
 
    private $tag; 
 
    private $content = array(); 
 
    
 
    function __construct($tag) { 
 
     $this->tag = $tag; 
 
    } 
 
    
 
    public function getContents() { 
 
     return $this->content; 
 
    } 
 
    
 
    protected function addContent($obj) { 
 
     $this->content[] = $obj; 
 
     return $obj; 
 
    } 
 

 
} 
 

 
final class batman extends heroes { 
 

 
    public function addPartner() { 
 
     return $this->addContent(new robin()); 
 
    } 
 
} 
 

 
final class robin extends heroes { 
 

 
    private $capes; 
 
    
 
    public function dieAtFirstFight() { 
 
     return BATMAN OBJ??? 
 
    } 
 
    
 
} 
 

 
$batman = new batman(); 
 
$batman = $batman->addPartner()->dieAtFirstFight(); 
 

 
?>

나는 $ self (배트맨 객체)를 설정하지만 PHP 오류 로그에 파트너를 추가 할 때마다 $ father라는 private 메소드를 추가하려고했으나 "Object of class 배트맨을 문자열로 변환 할 수 없습니다. "

+0

결국 영웅에 "파트너"필드를 추가하는 방법에 대한가없는 모든 영웅에 공통적 인 방법은? – Vini

답변

1

U는"$ t 그의 "아버지를 추가 할 수 있습니다. PHP에는 $ self가 없습니다.

<?php 
 

 
abstract class heroes { 
 
    private $tag; 
 
    private $content = array(); 
 
    protected $father; 
 
    
 
    function __construct($tag) { 
 
     $this->tag = $tag; 
 
    } 
 
    
 
    public function getContents() { 
 
     return $this->content; 
 
    } 
 
    
 
    protected function addContent($obj) { 
 
     $this->content[] = $obj; 
 
     $obj->setFather($this); 
 
     return $obj; 
 
    } 
 
    
 
    protected function setFather($father) { 
 
     $this->father = $father; 
 
    } 
 

 
} 
 

 
final class batman extends heroes { 
 

 
    public function addPartner() { 
 
     return $this->addContent(new robin('tag')); 
 
    } 
 
} 
 

 
final class robin extends heroes { 
 

 
    private $capes; 
 
    
 
    public function dieAtFirstFight() { 
 
     return $this->father; 
 
    } 
 
    
 
} 
 

 
$batman = new batman('tag'); 
 
$batman = $batman->addPartner()->dieAtFirstFight(); 
 

 
?>

+0

감사합니다. Meffen, 나는 내 대답에서 오류를 범했지만 실제로 $ self 대신 $ this를 사용했지만 오류는 $ father 선언의 "protected"가 아니 었습니다. 아버지가 개인적으로 오류를 생성 한 경우 보호 된 모든 것이 정상적으로 처리됩니다. 왜 그런지 알아? – prelite