문제

<?php

    class A{

     //many properties
     protected $myProperty1;
     protected $myProperty2;
     protected $myProperty3; 

     public function __construct(){
      $this->myProperty1='some value';
      $this->myProperty2='some value';
      $this->myProperty3='some value';
     }

     public function getProperty1(){
      return $this->myProperty1;
     }
     public function getProperty2(){
      return $this->myProperty2;
     }
     public function getProperty3(){
      return $this->myProperty3;
     }

     //edited: I added some setters, meaning that the object returned from the functions may already have these properties altered

     public function setProperty1($p){
      $this->myProperty1=$p;
     }
     public function setProperty2($p){
      $this->myProperty2=$p;
     }
     public function setProperty3($p){
      $this->myProperty3=$p;
     }


    }

    class B extends A{

     private $myProperty4;

     public function __construct(A $a){
      $this=$a; //this line has error,it says $this cannot be re-assigned
      $this->myProperty4='some value';
     }

     public function getProperty4(){
      return $this->myProperty4;
     }   
    }

   //$a = new A();
   $a = someClass::getAById(1234); //edited: $a is returned by a function (I cannot modify it)
   $b= new B($a); //error

?>

A의 객체를 B의 생성자에게 전달하여 B의 객체를 만들고 싶습니다. 보시다시피,이 변수를 다시 할 수는 없습니다. A에 많은 속성이 있으면 클래스 A를 수정할 수 없습니다. B의 생성자에서 이와 같은 일을하는 것이 지루할 것입니다.

 public function __construct(A $a){

  parent::__construct();
  $this->myProperty1=$a->getProperty1(); 
  $this->myProperty2=$a->getProperty2();
  $this->myProperty3=$a->getProperty3();

  $this->myProperty4='some value';

 }

내 질문은 최소한의 코딩을 가진 A의 객체를 사용하여 클래스 B의 객체를 어떻게 안전하게 만들 수 있습니까?

도움이 되었습니까?

해결책

class A
{
  public $property = 'Foobar';
}

class B extends A
{
  public function __construct()
  {
    echo $this->property; // Foobar
  }
}

내가 뭔가를 놓치고 있습니까? OOP가 의도하지 않은 일을하도록 강요하거나 상속을 이해하는 데 어려움을 겪고있는 것 같습니다.

클래스 A의 모든 대중 또는 보호 된 방법과 속성은 클래스 B에서 (내 예에서와 같이) 직접 참조하거나 부모 :: 구문을 사용하여 사용할 수 있습니다.

편집하다

(저자 명확한 질문)

클래스 A 속성에 액세스 할 수있는 경우 다음과 같은 것을 사용하여 클래스 B에 복사 할 수 있습니다.

class B
{
  public function __construct()
  {
    $a = new A(); // Or however A is instantiated
    foreach(get_object_vars($a) as $key => $value)
    {
      $this->$key = $value;
    }
  }
}

다른 팁

B가 A를 연장하기 때문에 왜 B를 만들지 않습니까? 추가 속성을 초기화 해야하는 경우 다음과 같이 생성자를 과도하게 승차 할 수 있습니다.

class B extends A {
    public function __construct(){
      parent::__construct(); //calls A's constructor
      $this->Bproperty='somevalue';
    }

}

그것이 충분하지 않다면, 당신은 반사를보고 싶을 것입니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top